Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 cumulative sum column)

num cumulative
1    1
2    3
3    6
5    11
6    17
8    25

This is one solution I got:

select a.num, sum(b.num) from ID a, ID b where b.num <= a.num group by a.num order by a.num;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
2.3k views
Welcome To Ask or Share your Answers For Others

1 Answer

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...