Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL select "accumulated" column

Tags:

mysql

I'm not sure what to call this besides an "accumulated" column.

I have a MySQL table with a column that looks like

+---+
|val|
+---+
| 1 |
| 4 |
| 6 |
| 3 |
| 2 |
| 5 |
+---+

I want to do a query so that I get this column along with another column which is the sum of all the rows from this column so far. In other words, the select would yield

+---+----+
|val| sum|
+---+----+
| 1 |  1 |
| 4 |  5 |
| 6 | 11 |
| 3 | 14 |
| 2 | 16 |
| 5 | 21 |
+---+----+

Does anyone know how I would do this, and whether you can do this in MySQL?

like image 717
Marquis Wang Avatar asked Jul 16 '09 05:07

Marquis Wang


1 Answers

What about

set @running_sum=0
select val, @running_sum:=@running_sum + val from your_table;

I'm new to mysql so take what I say with a grain of salt.

What you want is called a running sum. There are some google results.

like image 122
seth Avatar answered Oct 13 '22 23:10

seth