MySQL 滚动总和
MySQL Rolling SUM
例如我有波纹管 table
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 我想知道两者之间是否有中间地带来测试这些查询。
在大多数数据库中,您可以使用 window 函数:
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);
例如我有波纹管 table
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 我想知道两者之间是否有中间地带来测试这些查询。
在大多数数据库中,您可以使用 window 函数:
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);