first of all sorry for my english
I try to find a requete which calculate the sum of values in different rows like that :
row1 result
2 2
5 7
7 14
SUM() function. MySQL SUM() function returns the sum of an expression. SUM() function returns NULL when the return set has no rows.
To create a cumulative sum column in MySQL, you need to create a variable and set to value to 0. Cumulative sum increments the next value step by step with current value.
You can now add an order by to the over( partition by and it will do a cumulative sum of the previous rows. I had used the over( partition by with a row_number before, but not to do a cumulative sum over previous rows.
COUNT() is used to count the number of rows for a given condition. COUNT() works on numeric as well as non-numeric values. SUM() is used to calculate the total sum of all values in the specified numeric column.
Assuming that the first row defines the ordering, you can do this easily with a correlated subquery:
select r.row1,
(select sum(t2.row1) from requete r2 where r2.row1 <= r.row1) as cumesum
from requete r;
For a larger table, this might be inefficient, and variables would improve performance:
select r.row1,
(@sum := @sum + r.row1) as cumesum
from requete r cross join
(select @sum := 0) params
order by r.row1;
Note in both cases the column used for ordering the rows does not need to be the same column for the cumulative sum calculation.
EDIT:
In MySQL 8+, you should of course use:
select r.row1,
sum(row1) over (order by row1) as cumesum
from requete r;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With