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
  • 44,943
  • 6
  • 31
  • 51

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,242,037
  • 58
  • 646
  • 786
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
  • 306
  • 1
  • 2
  • 13
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
  • 38,771
  • 9
  • 70
  • 114