Calculate moving averages in SQL

前端 未结 1 1061
再見小時候
再見小時候 2021-01-06 17:50

I want to calculate a 12 month moving average from a MySQL column. The data represents time-series power measurements, it is a largish dataset (every 10 minutes for several

1条回答
  •  囚心锁ツ
    2021-01-06 18:01

    Try:

    SELECT YEAR(GDTE) AS year, 
           MONTH(GDTE) AS month, 
           SUM(case when i=0 then Active end)/6 as total,
           SUM(Active)/(MAX(i+1)*6) as avg
    FROM
    (select s.*, DATE_ADD(DTE, INTERVAL m.i MONTH) GDTE, m.i
     FROM saturne s
     cross join (select 0 i union select 1 union select 2 union select 3 union 
                 select 4 union select 5 union select 6 union select 7 union 
                 select 8 union select 9 union select 10 union select 11) m
    ) sq
    WHERE GDTE <= curdate()
    GROUP BY YEAR(GDTE), MONTH(GDTE)
    

    0 讨论(0)
提交回复
热议问题