6

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
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786

1 Answers1

16

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;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786