mwafi mwafi - 6 days ago 6
MySQL Question

MySQL: select and SUM previous values in specific column

Is there a way to select values from table and sum all previous values?

table sample:

+-------------+
| id | Amount |
+-------------+
| 1 | 10 |
| 2 | 10 |
| 3 | 10 |
| 4 | 10 |
| 5 | 10 |
| 6 | 10 |
| 7 | 10 |
+----+--------+


Is there a way to select data from the table and sum "Amount" values (sum all previous ):

+-------------+
| id | Amount |
+-------------+
| 1 | 10 |
| 2 | 20 |
| 3 | 30 |
| 4 | 40 |
| 5 | 50 |
| 6 | 60 |
| 7 | 70 |
+----+--------+


thx,

Answer

In MySQL, the most efficient way to do this uses variables:

select id, amount, (@sum := @sum + amount) as running_amount
from t cross join
     (select @sum := 0) params
order by id;
Comments