views:

49

answers:

3

I have a MySQL table like the following:

date         count
2010-01-01   5
2010-01-02   6
2010-01-03   7

How can I accumulate the sum of each day to the next one? So the result is like:

date         acum per day
2010-01-01   5
2010-01-02   11
2010-01-03   18

I think i need some kind of for(each date)... but no clue.


Just the final query i used following answer from Eric. (thanks).

SELECT t1.dia, sum(t2.operacions), sum(t2.amount) FROM

(SELECT count(*) operations, sum(amount), date(b.timestamp) dia
    FROM transactions b group by date(b.timestamp)) t1 

INNER JOIN 

(SELECT count(*) operations, sum(amount), date(b.timestamp) dia
    FROM transactions b group by date(b.timestamp)) t2 

ON t2.dia <= t1.dia GROUP BY t1.dia
+2  A: 

Well, I think this would work, not sure how the performance would be though:

SELECT t1.date, sum(t2.count)
FROM mytable t1 INNER JOIN mytable t2 ON t2.date <= t1.date
GROUP BY t1.date
Eric Petroelje
That assumes that all the `date` data is either a DATETIME data type, for the exact same time, or the column is [var]char which risks not evaluating correctly on the join.
OMG Ponies
@Ponies - That's right, if there was a time component to the date he would need to do some conversions to get just the date part. Since he showed only dates in his question, I assumed that was all he was storing.
Eric Petroelje
@Ponies - Also, Even if it's VARCHAR, looks like he's using YYYY-MM-DD format, so they should compare correctly even as strings.
Eric Petroelje
@Eric: OP updated, it's a timestamp/datetime
OMG Ponies
This worked for me. Not aware it was possible to do this kind of conditional join! Very useful. Thanks.
A: 

Self join with a <= and sum the row would accomplish this.

buckbova
A: 

It's possible to solve this problem without join.

SET @cumulative_sum := 0;
SELECT date, @cumulative_sum := @cumulative_sum + count AS cumulative_sum
FROM table
ORDER BY date ASC
Naktibalda