我的数据集如下:
Date Price 3 Day Moving Average ------------------------------------------------- 2018-08-01 10 2018-08-02 12 2018-08-03 11 11 (10+12+11)/3\n 2018-08-04 15 12.67 (12+11+15)/3 2018-08-05 13 13 (11+15+13)/3 2018-08-06 17 ... 2018-08-07 18 … 2018-08-08 20 ..
仅使用MySQL窗口函数可以做到这一点吗?
服务器版本:8.0.12 MySQL Community Server-GPL
您可以将Window Functions与Frames一起使用:
SELECT Date, Price, CASE WHEN ROW_NUMBER() OVER (ORDER BY DATE) >= 3 THEN AVG(Price) OVER (ORDER BY Date ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) ELSE NULL END AS avg FROM yourTable ORDER BY Date;
细节:
2 PRECEDING
Date
CURRENT ROW
BETWEEN
null
Row_number()
Case .. When