计算移动平均
管理层不再想看从最初到现在的累积总数,而是希望看到过去 7 天的事件数「平均值」——也就是从 6 天前开始,到当前日期结束。由于这是在查询过程中不断滑动的固定窗口上计算,因此称为「移动平均」。
SQL Server 无法在窗口函数中按时间区间直接定义范围,因此我们需要假设数据为「每日一行」,并使用 ROWS 子句来指定窗口框架。
本练习是课程的一部分
SQL Server 中的时间序列分析
练习说明
- 填写正确的窗口函数,实现从 6 天前到今天(当前行)的移动平均。
- 补全窗口框架,包括
ROWS子句、窗口的 preceding 与 following 定义。
交互式实操练习
通过完成这段示例代码来试试这个练习。
SELECT
ir.IncidentDate,
ir.IncidentTypeID,
ir.NumberOfIncidents,
-- Fill in the correct window function
___(ir.NumberOfIncidents) OVER (
PARTITION BY ir.IncidentTypeID
ORDER BY ir.IncidentDate
-- Fill in the three parts of the window frame
___ BETWEEN ___ AND ___
) AS MeanNumberOfIncidents
FROM dbo.IncidentRollup ir
INNER JOIN dbo.Calendar c
ON ir.IncidentDate = c.Date
WHERE
c.CalendarYear = 2019
AND c.CalendarMonth IN (7, 8)
AND ir.IncidentTypeID = 1
ORDER BY
ir.IncidentTypeID,
ir.IncidentDate;