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?
MySQL 8.0/MariaDB supports windowed
SUM(col) OVER()
:Output:
db<>fiddle
You could also create a trigger that will calculate the sum before each insert
I have not tested this
Sample query
If performance is an issue, you could use a MySQL variable:
Alternatively, you could remove the
cumulative_sum
column and calculate it on each query:This calculates the running sum in a running way :)