MySQL滚动SUM

时间:2017-10-09 11:46:54

标签: mysql sql amazon-web-services rollup

例如我有波纹管表

 DATE       QUANTITY
9/10/2017     3
9/10/2016     5
9/03/2015     6
9/10/2017     2
8/10/2017     9

我希望最终输出看起来如下

YEAR    MONTH   ROLLING SUM   SUM
2015     03          6         6
2016     10          11        5
2017     10          25        14

为了获得总和,我使用以下代码

SELECT YEAR(Date),MONTH(Date),SUM(QUANTITY) 
FROM table
GROUP BY YEAR(Date),MONTH(Date);

是否可以将Rollup Sum添加到同一个查询中?

作为第二个注释: 目前我正在使用MySQL,但这些查询将运行的最终环境是AWS Athena.And我想知道两者之间是否存在中间立场来测试这些查询。

1 个答案:

答案 0 :(得分:0)

在大多数数据库中,您可以使用窗口函数:

SELECT YEAR(Date), MONTH(Date), SUM(QUANTITY),
       SUM(SUM(QUANTITY)) OVER (ORDER BY YEAR(DATE), MONTH(DATE) 
FROM table
GROUP BY YEAR(Date),MONTH(Date);

在MySQL中,我建议使用相关的子查询:

SELECT YEAR(Date), MONTH(Date), SUM(QUANTITY),
       (SELECT SUM(t2.QUANTITY)
        FROM table t2
        WHERE YEAR(t2.Date) < YEAR(t.Date) OR
              (YEAR(t2.Date) = YEAR(t.Date) AND MONTH(t2.Date) <= MONTH(t.date))
       ) as rolling_sum
FROM table t
GROUP BY YEAR(Date), MONTH(Date);