Create a ROLLING sum over a period of time in mysql

末鹿安然 提交于 2020-01-11 10:48:12

问题


I have a table with columns date and time_spent. I want to find for each date D the sum of the values of 'time_spent' for the period of time : (D-7 - D), ie. past week + current day.

I can't figure out a way to do this, as I can only find examples for a total sum and not a sum over a variable period of time.

Here is a dataset example :

CREATE TABLE rolling_total
(
  date date,
  time_spent int
);

INSERT INTO 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 would look like :

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
// now we omit values that are older than seven days
2013-09-09 |           1  |        21
2013-09-10 |           1  |        21
...

回答1:


And one more solution

SELECT r1.date, r1.time_spent, sum(r2.time_spent) AS rolling_week_total
FROM rolling_total AS r1 JOIN rolling_total AS r2
    ON datediff(r1.date, r2.date) BETWEEN 0 AND 7
GROUP BY r1.date
ORDER BY r1.date
LIMIT 8



回答2:


Here you go:

select
t.*,
@total:=@total + t.time_spent - coalesce(t2.time_spent, 0) as your_total_over_last_7_days
from
rolling_total t
left join rolling_total t2 on t.date = t2.date + interval 8 day
, (select @total:=0) v
order by t.`date` 
  • see it working live in an sqlfiddle.



回答3:


Here is another solution

SELECT r1.date, r1.time_spent, 
   ( SELECT SUM(time_spent) 
     FROM rolling_total AS r2
     WHERE datediff(r1.date, r2.date) 
     BETWEEN 0 AND 7
   ) AS rolling_week_total
FROM rolling_total AS r1  
ORDER BY r1.date
LIMIT 8


来源:https://stackoverflow.com/questions/19213633/create-a-rolling-sum-over-a-period-of-time-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!