Friday, December 9, 2011

Date wise cumulative count in Mysql


Date wise cumulative count

Dear all,
I can take date wise count using group by in mysql.But i want date wise cumulative count in mysql.How?

For example, 

date count 
10-11-2011 200 
11-11-2011 500 
12-11-2011 700 

This is day wise count. 

But i want day wise cumulative count. 

date count 
10-11-2011 200 
11-11-2011 700 
12-11-2011 1400 

like this.


Answer

You can do that with a self-join, but only works with a single value per day:

CREATE TABLE t1 (DateField TIMESTAMP, CountValue INT);
INSERT INTO t1 VALUE ("2011-11-10",200),("2011-11-11",500),("2011-11-12",700);

SELECT t1a.DateField, SUM(t1b.CountValue) FROM t1 t1a, t1 t1b WHERE t1a.DateField>=t1b.DateField GROUP BY t1a.DateField;

datefield sum(t1b.countvalue)
2011-11-10 200
2011-11-11 700
2011-11-12 1400

If you have more than one value per date, you can probably make it work with a derived table.

No comments:

Post a Comment