This is called cumulative sum.
In Oracle
and PostgreSQL
, it is calculated using a window function:
SELECT id, val, SUM() OVER (ORDER BY id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
FROM mytable
However, MySQL
does not support it.
In MySQL
, you can calculate it using session variables:
SET @s = 0;
SELECT id, val, @s := @s + val
FROM mytable
ORDER BY
id
;
or in a pure set-based but less efficient way:
SELECT t1.id, t1.val, SUM(t2.val)
FROM mytable t1
JOIN mytable t2
ON t2.id <= t1.id
GROUP BY
t1.id
;
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…