Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do a sum of previous rows in mysql a sum of previous rows [duplicate]

Tags:

sql

mysql

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
like image 390
Mohamed Amine Avatar asked Jul 05 '15 17:07

Mohamed Amine


People also ask

How can I sum two rows in MySQL?

SUM() function. MySQL SUM() function returns the sum of an expression. SUM() function returns NULL when the return set has no rows.

How do I accumulate a sum in MySQL?

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.

How do I add a previous row value in SQL?

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.

Can I do a sum of a count in MySQL?

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.


Video Answer


1 Answers

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;
like image 149
Gordon Linoff Avatar answered Nov 14 '22 07:11

Gordon Linoff