计算列中不同值的移动平均值 MySQL

Calculating moving average for different values in a column MySQL

我有这样的数据集:

team   date        score
A      2011-05-01    50
A      2011-05-02    54
A      2011-05-03    51
A      2011-05-04    49
A      2011-05-05    59
B      2011-05-03    30
B      2011-05-04    35
B      2011-05-05    39
B      2011-05-06    47
B      2011-05-07    50

我想添加另一个名为 MA3 的列,我可以在其中计算过去 3 天得分的移动平均值。棘手的一点是计算每个团队的 MA。最终结果应该是这样的:

team   date         score   MA3
A      2011-05-01    50    null
A      2011-05-02    54    null
A      2011-05-03    51    null
A      2011-05-04    49    51.66
A      2011-05-05    59    51.33
B      2011-05-03    30    null
B      2011-05-04    35    null
B      2011-05-05    39    null
B      2011-05-06    47    34.66
B      2011-05-07    50    40.33

如果那是一个团队,我会继续做:

SELECT team, 
       year,
       AVG(score) OVER (ORDER BY date ASC ROWS 3 PRECEDING) AS MA3
FROM   table

您缺少 PARTITION BY 子句:

SELECT team, 
       date,
       AVG(score) OVER (
         PARTITION BY team
         ORDER BY date ASC ROWS 3 PRECEDING
       ) AS MA3
FROM   table

请注意,无论 window 大小如何,总会进行平均计算。如果你希望平均值为 null 如果你的 window 大小小于 3,你可以这样做:

SELECT team, 
       date,
       CASE 
         WHEN count(*) OVER w <= 3 THEN null 
         ELSE AVG(score) OVER w
       END AS MA3
FROM   table
WINDOW w AS (PARTITION BY team ORDER BY date ASC ROWS 3 PRECEDING)

dbfiddle

旁注

您的下一个问题可能是关于 logical windowing,因为通常您实际上并不想计算 3 行的平均值,而是在某个时间间隔内, 像例如3天。幸运的是,MySQL 实现了这一点。然后你可以写:

WINDOW w AS (PARTITION BY team ORDER BY date ASC RANGE INTERVAL 3 DAY PRECEDING)