Calculating a Moving Average MySQL?

后端 未结 5 2052
半阙折子戏
半阙折子戏 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:39

    Use something like

    SELECT 
      sum(close) as sum,
      avg(close) as average
    FROM (
        SELECT 
          (close)
        FROM 
          tbl
        WHERE 
          date <= '2002-07-05'
          AND name_id = 2
        ORDER BY 
          date DESC
        LIMIT 9 ) temp
    

    The inner query returns all filtered rows in desc order, and then you avg, sum up those rows returned.

    The reason why the query given by you doesn't work is due to the fact that the sum is calculated first and the LIMIT clause is applied after the sum has already been calculated, giving you the sum of all the rows present

提交回复
热议问题