Create a ROLLING sum over a period of time in mysql

前端 未结 3 655

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

相关标签:
3条回答
  • 2020-12-21 16:56

    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
    
    0 讨论(0)
  • 2020-12-21 17:04

    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
    
    0 讨论(0)
  • 2020-12-21 17:08

    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.
    0 讨论(0)
提交回复
热议问题