Read 298 times | Created 2017-12-22 02:35:36 | Updated 2018-10-29 17:59:55 | | |

 

DROP TABLE IF EXISTS a;
CREATE TABLE a(
    id INT AUTO_INCREMENT PRIMARY KEY,
    amount INT
);

INSERT INTO a(amount) VALUES
(3),(9),(2),(5),(4),(8);

SELECT * FROM a;

+----+--------+
| id | amount |
+----+--------+
|  1 |      3 |
|  2 |      9 |
|  3 |      2 |
|  4 |      5 |
|  5 |      4 |
|  6 |      8 |
+----+--------+
6 rows in set (0.00 sec)

SELECT
    a.*,(@s:=@s+amount) AS cumulative_sum
FROM
    a,(SELECT @s:=0) b
ORDER BY a.id;

+----+--------+----------------+
| id | amount | cumulative_sum |
+----+--------+----------------+
|  1 |      3 |              3 |
|  2 |      9 |             12 |
|  3 |      2 |             14 |
|  4 |      5 |             19 |
|  5 |      4 |             23 |
|  6 |      8 |             31 |
+----+--------+----------------+
6 rows in set (0.00 sec)