Table t1:
date       profit
2011-01-01  100
2011-01-02  -50
2011-01-03   25
I'd like to get an output like:
date       aggregated profit
2011-01-01  100
2011-01-02   50
2011-01-03   75
Any suggestion for an efficient MySQL query?
Table t1:
date       profit
2011-01-01  100
2011-01-02  -50
2011-01-03   25
I'd like to get an output like:
date       aggregated profit
2011-01-01  100
2011-01-02   50
2011-01-03   75
Any suggestion for an efficient MySQL query?
You are looking for a cumulative sum. The most efficient method uses variables:
select t.*, (@sum := @sum + profit) as cumulative_profit
from (select t.*
      from t
      order by date
     ) t cross join
     (select @sum := 0) params;
Note that in earlier versions of MySQL, the subquery is not necessary. Somewhere around 5.7, the subquery became needed for the variable to respect the ordering.