2

lets say i have data in mysql like this :

date | value
2010 | 1
2011 | 4
2012 | 2
2013 | 3

i want the result like this :

date | value
2010 | 1
2011 | 5
2012 | 7
2013 | 10

I thought this would be simple. I'm trying this:

select tabelA.date, sum(value)
from tabelA
inner join (select date from tabelA group by date) b on tabelA.date > b.date
group by tabelA.date

I feel like I'm missing something obvious. It seems like a simple thing to want to do.

Any ideas?

D-Shih
  • 42,799
  • 6
  • 22
  • 44

3 Answers3

1

The best approach in MySQL 8+ is window functions:

select a.date,
       sum(a.value) over (order by a.date)
from tabelA a
order by a.date;

In older versions, variables are probably the best approach, but they have to be used carefully:

select date, (@csum := @csum + value) as running_sum
from (select a.date, a.value as value
      from tableA a
      order by a.date
     ) a cross join
     (select @csum := 0) params;

In particular, you want the order by in the subquery to be sure that the data is processed in the correct order.

Gordon Linoff
  • 1,198,228
  • 53
  • 572
  • 709
0
SELECT
    b.date,( SELECT sum( a.`value` ) FROM aa a WHERE a.date <= b.date ) value
FROM
    aa b 
GROUP BY
    b.date
wl.GIG
  • 266
  • 2
  • 12
0

You could use a variable:

SET @cumulative := 0;
SELECT date, (@cumulative := @cumulative+value) as value FROM tabelA

This will just keep track of current sum. It's basically a minor adaptation of this answer to get a row number.

apokryfos
  • 34,925
  • 8
  • 65
  • 98