admin管理员组文章数量:1397110
I have created 2 temporary tables that aggregate data. One is payment data where I have created a sum by month_year, and one is savings made aggregated in the same way.
Query:
WITH PAYMENT
(SELECT
year_month
,SUM(AMOUNT) PAYMENT_AMOUNT
FROM PAYMENTS
GROUP BY ROLLUP (year_month))
,SAVING
(SELECT
year_month
,SUM(AMOUNT) SAVING_AMOUNT
FROM SAVING
GROUP BY ROLLUP (year_month))
SELECT payment.year_month, PAYMENT_AMOUNT, SAVING_AMOUNT,SAVING_AMOUNT/PAYMENT_AMOUNT PERC_SAVED FROM PAYMENT
LEFT JOIN SAVINGS ON PAYMENT.YEAR_MONTH=SAVINGS.YEAR_MONTH
The issue that I have is that the savings amount for the total created from the rollup does not join. I have used an IFNULL(year_month, 'Total') on both tables to create an alias to join, and coalesce(year_month, 'Total'), but I only get;
enter image description here
Whereas the result that I want is;
enter image description here
I have created 2 temporary tables that aggregate data. One is payment data where I have created a sum by month_year, and one is savings made aggregated in the same way.
Query:
WITH PAYMENT
(SELECT
year_month
,SUM(AMOUNT) PAYMENT_AMOUNT
FROM PAYMENTS
GROUP BY ROLLUP (year_month))
,SAVING
(SELECT
year_month
,SUM(AMOUNT) SAVING_AMOUNT
FROM SAVING
GROUP BY ROLLUP (year_month))
SELECT payment.year_month, PAYMENT_AMOUNT, SAVING_AMOUNT,SAVING_AMOUNT/PAYMENT_AMOUNT PERC_SAVED FROM PAYMENT
LEFT JOIN SAVINGS ON PAYMENT.YEAR_MONTH=SAVINGS.YEAR_MONTH
The issue that I have is that the savings amount for the total created from the rollup does not join. I have used an IFNULL(year_month, 'Total') on both tables to create an alias to join, and coalesce(year_month, 'Total'), but I only get;
enter image description here
Whereas the result that I want is;
enter image description here
Share Improve this question edited Mar 26 at 12:05 Paul T. 4,95212 gold badges47 silver badges63 bronze badges asked Mar 26 at 11:54 David ManDavid Man 12 bronze badges1 Answer
Reset to default 0rollup will produce a null year_month for the total, which will not match, however you can use coalesce to match with the following BigQuery SQL
WITH PAYMENT
(
SELECT year_month
,SUM(AMOUNT) PAYMENT_AMOUNT
FROM PAYMENTS
GROUP BY ROLLUP (year_month)
)
,SAVING
(
SELECT year_month
,SUM(AMOUNT) SAVING_AMOUNT
FROM SAVING
GROUP BY ROLLUP (year_month)
)
SELECT COALESCE(payment.year_month, savings.year_month, 'TOTAL') year_month,
PAYMENT_AMOUNT,
SAVING_AMOUNT,
SAVING_AMOUNT/PAYMENT_AMOUNT PERC_SAVED
FROM PAYMENT
LEFT JOIN SAVINGS ON COALESCE(payment.year_month, 'TOTAL') = COALESCE(savings.year_month, 'TOTAL');
producing this
本文标签: Joining 2 tables on Grouping Setrollup total row on BigQueryStack Overflow
版权声明:本文标题:Joining 2 tables on Grouping Setrollup total row on BigQuery - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744146981a2592882.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论