Creating a cumulative sum column in MySQL

前端 未结 4 423
野性不改
野性不改 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:32

    Since MySQL 8, cumulative sums are ideally calculated using window functions. In your case, run:

    SELECT num, SUM(num) OVER (ORDER BY num) cumulative
    FROM id
    

提交回复
热议问题