sql - Create a ROLLING sum over a period of time in mysql -


i have table columns date , time_spent. want find each date d sum of values of 'time_spent' period of time : (d-7 - d), ie. past week + current day.

i can't figure out way this, can find examples total sum , not sum on variable period of time.

here dataset example :

create table rolling_total (   date date,   time_spent int );  insert rolling_total values ('2013-09-01','2'), ('2013-09-02','1'), ('2013-09-03','3'), ('2013-09-04','4'), ('2013-09-05','2'), ('2013-09-06','5'), ('2013-09-07','3'), ('2013-09-08','2'), ('2013-09-09','1'), ('2013-09-10','1'), ('2013-09-11','1'), ('2013-09-12','3'), ('2013-09-13','2'), ('2013-09-14','4'), ('2013-09-15','6'), ('2013-09-16','1'), ('2013-09-17','2'), ('2013-09-18','3'), ('2013-09-19','4'), ('2013-09-20','1'), ('2013-09-21','6'), ('2013-09-22','5'), ('2013-09-23','3'), ('2013-09-24','1'), ('2013-09-25','5'), ('2013-09-26','2'), ('2013-09-27','1'), ('2013-09-28','4'), ('2013-09-29','3'), ('2013-09-30','2') 

result :

date       | time_spent   | rolling_week_total 2013-09-01 |           2  |         2 2013-09-02 |           1  |         3 2013-09-03 |           3  |         6 2013-09-04 |           4  |        10 2013-09-05 |           2  |        12 2013-09-06 |           5  |        17 2013-09-07 |           3  |        20 2013-09-08 |           2  |        22 // omit values older 7 days 2013-09-09 |           1  |        21 2013-09-10 |           1  |        21 ... 

and 1 more solution

select r1.date, r1.time_spent, sum(r2.time_spent) rolling_week_total rolling_total r1 join rolling_total r2     on datediff(r1.date, r2.date) between 0 , 7 group r1.date order r1.date limit 8 

Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -