I have a table that looks like this:
id count
1 100
2 50
3 10
I want to add a new column called cumulative_sum, so the table would look like this:
id count cumulative_sum
1 100 100
2 50 150
3 10 160
Is there a MySQL update statement that can do this easily? What's the best way to accomplish this?
Using a correlated query:
Using MySQL variables:
Note:
JOIN (SELECT @running_total := 0) r
is a cross join, and allows for variable declaration without requiring a separateSET
command.r
, is required by MySQL for any subquery/derived table/inline viewCaveats:
ORDER BY
is important; it ensures the order matches the OP and can have larger implications for more complicated variable usage (IE: psuedo ROW_NUMBER/RANK functionality, which MySQL lacks)