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

Categories

0 votes
2.6k views
in Technique[技术] by (71.8m points)

sql - Creating a cumulative sum column in MySQL

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...