Create a column for cumulative sum in MySQL
P粉670838735
2023-08-22 11:26:08
<p>I have a table that looks like this:</p>
<pre class="brush:php;toolbar:false;">id count
1 100
2 50
3 10</pre>
<p>I want to add a new column called cumulative_sum, so the table looks like this: </p>
<pre class="brush:php;toolbar:false;">id count cumulative_sum
1 100 100
2 50 150
3 10 160</pre>
<p>Is there a MySQL update statement that can easily achieve this? What's the best approach? </p>
Use related queries:
Use MySQL variables:
Notice:
JOIN (SELECT @running_total := 0) r
is a cross join that allows variables to be declared without the need for a separateSET
command.r
Precautions:
ORDER BY
is very important, it ensures that the order matches the original question, and may have a greater impact for more complex variable usage (eg: pseudo-ROW_NUMBER/RANK functionality, not supported by MySQL)If performance is an issue, you can use MySQL variables:
Alternatively, you can remove the
cumulative_sum
column and calculate it in every query:This calculates the cumulative sum in a continuous manner :)