SQL 合计获得每月和每年

SQL aggregate get monthly and yearly

我正在尝试获取每月总计的汇总,并将每年总计的额外行添加到同一个 SQL 查询中。

Table table_1

id    date        amount   currency

 1    2017-01-01  76.89     CAD
 2    2017-01-17  90.89     CAD
 3    2017-01-18  65        USD
 4    2017-05-13  45        CAD
 5    2017-07-19  76.70     CAD
 6    2018-08-13  67.34     CAD
 7    2018-09-11  50        CAD
 8    2018-09-09  45        CAD
 9    2018-08-12  67        CAD
 10   2018-07-10  55        USD
 11   2018-07-11  13        USD

我已经尝试使用此查询获取每月总计并按货币分组。

    SELECT SUM(amount),
           currency, 
           MONTH(date)
   FROM invoices 
   GROUP BY MONTH(date), YEAR(date), currency

我想要的结果原型

prototype of result

谢谢

整年的行在月份列中包含 NULL

SELECT MONTH(date) AS Month,
       YEAR(date) AS Year,
       currency AS Currency,
       SUM(amount) AS Total
FROM invoices 
GROUP BY MONTH(date), YEAR(date), currency
UNION ALL
SELECT NULL, YEAR(date), currency, SUM(amount)
FROM invoices 
GROUP BY YEAR(date), currency
ORDER BY Year, Month IS NULL, Month

你可以找到一个演示 here

编辑:根据要求对结果集进行排序

EDIT2:我还是不明白为什么以前的解决方案不能接受,我稍微调整了一下,使其与结果的新原型重合

SELECT 列或 ORDER 列的顺序可能与 GROUP 它们的顺序不同。

然后您可以使用 GROUP BY WITH ROLLUP 并使用 GROUPING() 检查什么是 super-aggregate 以选择要聚合到的级别以及显示所有内容的顺序。

SELECT
   YEAR(date),
   MONTH(date),
   currency,
   SUM(amount)
FROM
   invoices
GROUP BY
   currency,
   YEAR(date),
   MONTH(date)
WITH
   ROLLUP
HAVING
   GROUPING(Currency) = 0  -- don't ROLLUP the currency
ORDER BY
   GROUPING(YEAR(date)),  -- individual years first, super-aggregate last
   YEAR(date),
   GROUPING(MONTH(date)), -- individual months first, super-aggregate last
   MONTH(date),
   currency