MySQL 5分钟移动平均线(按日期范围分组行)

时间:2017-09-03 04:10:57

标签: mysql moving-average

我正试图从以下格式的数据中获得5分钟移动平均价格的5长度:

ID,价格,时间表

1   15.36573000 2017-08-31 22:00:00
1   15.29229000 2017-08-31 21:55:00
1   15.23297000 2017-08-31 21:50:00
1   15.23469000 2017-08-31 21:45:00
1   15.23234000 2017-08-31 21:40:00
1   15.25399000 2017-08-31 21:35:00
1   15.26228000 2017-08-31 21:30:00
1   15.21136000 2017-08-31 21:25:00
1   15.29847000 2017-08-31 21:20:00
1   15.32074000 2017-08-31 21:15:00
1   15.32239000 2017-08-31 21:10:00
1   15.27938000 2017-08-31 21:05:00
1   15.25282000 2017-08-31 21:00:00

所以9个时间段(45分钟)的平均值是:

8/31/2017 21:45 through 8/31/2017 21:05 = 15.26840444
8/31/2017 21:40 through 8/31/2017 21:00 = 15.27041889
8/31/2017 21:35 through 8/31/2017 20:55 = 15.27291889

我白天看到了一些移动平均线,但无法确定如何按最后9个时间戳分组

1 个答案:

答案 0 :(得分:0)

在MySQL中处理此问题的一种方法是通过相关子查询。请注意,在下面的查询中,我不计算先前数据点的数量,而是依赖于时间差(40分钟)。这似乎更有意义,因为您的数据可能并不总是具有相同的点数。

SELECT
    CONCAT(CAST(t1.timeline - INTERVAL 40 MINUTE AS CHAR(50)), ' through ',
           CAST(t1.timeline AS CHAR(50))) AS window,
    (SELECT AVG(t2.price) FROM yourTable t2
     WHERE t2.timeline
         BETWEEN t1.timeline - INTERVAL 40 MINUTE AND t1.timeline) AS avg_price
FROM yourTable t1
WHERE
    t1.timeline >= (SELECT MIN(timeline) + INTERVAL 40 MINUTE FROM yourTable)
ORDER BY t1.timeline

在这里演示:

Rextester