Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a cumulative sum column in MySQL

Tags:

sql

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;
like image 689
varunl Avatar asked Dec 21 '22 08:12

varunl


1 Answers

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;
like image 85
The Scrum Meister Avatar answered Dec 25 '22 23:12

The Scrum Meister