How to calculated multiple moving average in MySQL

后端 未结 3 1105
Happy的楠姐
Happy的楠姐 2020-12-11 23:49

Using table below, How would get a column for 5 period moving average, 10 period moving average, 5 period exponential moving average.

+--------+------------         


        
相关标签:
3条回答
  • 2020-12-12 00:03
    SELECT AVG(a.price) FROM (SELECT price FROM t1 WHERE data_date <= ? ORDER BY data_date DESC LIMIT 5) AS a;
    

    Replace ? with the date whose MA you need.

    0 讨论(0)
  • 2020-12-12 00:16
    SELECT   t1.data_date, 
    ( SELECT  SUM(t2.price) / COUNT(t2.price) as MA5 FROM mytable AS t2    WHERE DATEDIFF(t1.data_date, t2.data_date) BETWEEN 0 AND 6 ) 
    FROM mytable AS t1   ORDER BY t1.data_date;
    

    Change 6 to 13 for 10-day MA

    0 讨论(0)
  • 2020-12-12 00:17

    The 5-row moving average in your example won't work. The LIMIT operator applies to the return set, not the rows being considered for the aggregates, so changing it makes no difference to the aggregate values.

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