Creating a cumulative sum column in MySQL

前端 未结 4 410
野性不改
野性不改 2020-12-21 04:07

Sample table ID: (num is a key so there wouldn\'t be any duplicates)

num
1
5
6
8
2
3

Desired output:
(Should be sorted and have a cumul

4条回答
  •  春和景丽
    2020-12-21 04:19

    You can use a temporary variable to calculate the cumulative sum:

    SELECT  a.num,
       (@s := @s + a.num) AS cumulative
    FROM ID a, (SELECT @s := 0) dm
    ORDER BY a.num;
    

提交回复
热议问题