Create cumulative sum column in MySQL
When processing data sets, it is often necessary to calculate the cumulative sum. In MySQL, this can be achieved in several ways.
Use related query
Related queries involve referencing data from other rows in the same query. To create a cumulative sum column using this method:
<code class="language-sql">SELECT t.id, t.count, (SELECT SUM(x.count) FROM TABLE x WHERE x.id <= t.id) AS cumulative_sum FROM TABLE t ORDER BY t.id;</code>
Using MySQL variables
MySQL variables can also be used for cumulative sum calculations. This involves declaring a variable and incrementing it in the query:
<code class="language-sql">SELECT t.id, t.count, @running_total := @running_total + t.count AS cumulative_sum FROM TABLE t JOIN (SELECT @running_total := 0) r ORDER BY t.id;</code>
Note that cross joins (SELECT @running_total := 0) r
are used to declare variables.
Notes
ORDER BY
clause is crucial, ensuring the correct order of calculations. The above is the detailed content of How Can I Calculate Cumulative Sums in MySQL?. For more information, please follow other related articles on the PHP Chinese website!