Calculating a Moving Average MySQL?

后端 未结 5 2047
半阙折子戏
半阙折子戏 2020-11-28 15:03

Good Day,

I am using the following code to calculate the 9 Day Moving average.

SELECT SUM(close)
FROM tbl
WHERE date <= \'2002-07-05\'
AND name_id         


        
5条回答
  •  [愿得一人]
    2020-11-28 15:46

    If you want the moving average for each date, then try this:

    SELECT date, SUM(close),
           (select avg(close) from tbl t2 where t2.name_id = t.name_id and datediff(t2.date, t.date) <= 9
           ) as mvgAvg
    FROM tbl t
    WHERE date <= '2002-07-05' and
          name_id = 2
    GROUP BY date
    ORDER BY date DESC
    

    It uses a correlated subquery to calculate the average of 9 values.

提交回复
热议问题