Calculating a Moving Average MySQL?

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.

Leave a Comment