SQL 5.7 组的累计总和

Cumulative sum over groups on SQL 5.7

我在 MySQL 5.7 上工作,table 看起来像这样:

 num  id   count
 1    1    100
 2    1    50
 1    2    10
 2    2    100
 1    3    50
 2    3    10

我想添加一个名为 cumulative_sum 的新列,因此 table 将如下所示:

num id   count  cumulative_sum
1   1    100    100
2   1    50     150
1   2    10     10
2   2    100    120
1   3    50     50
2   3    10     60

是否有 MySQL 更新语句可以轻松做到这一点?完成此任务的最佳方法是什么?我找到的最多示例是定义的变量或子查询。

在 MySQL 5.7 上,我们可以使用相关子查询来查找滚动总和:

SELECT
    id,
    count,
    (SELECT SUM(t2.count) FROM yourTable t2
     WHERE t2.id = t1.id AND t2.num <= t1.num) cumulative_sum
FROM yourTable t1
ORDER BY
    id,
    num

在MySQL8+上,我们可以使用SUM作为解析函数:

SELECT
    id,
    count,
    SUM(count) OVER (PARTITION BY id ORDER BY num) cumulative_sum
FROM yourTable
ORDER BY
    id,
    num;