查看前后期间的数据
LAG() 和 LEAD() 窗口函数分别支持向后或向前查看时间序列数据。这样您就能在一条简单的查询中进行环比比较。
在本练习中,您需要比较 2019 年 7 月期间(具体为 7 月 2 日至 7 月 31 日)的每日安全事件数量,事件类型为 1 和 2。
本练习是课程的一部分
SQL Server 中的时间序列分析
练习说明
- 补全窗口函数以返回前一日的事件数量,按事件类型 ID 分区,并按事件日期排序。
- 补全窗口函数以返回下一日的事件数量,按事件类型 ID 分区,并按事件日期排序。
交互式实操练习
通过完成这段示例代码来试试这个练习。
SELECT
ir.IncidentDate,
ir.IncidentTypeID,
-- Get the prior day's number of incidents
___(ir.___, ___) OVER (
-- Partition by incident type ID
PARTITION BY ir.___
-- Order by incident date
ORDER BY ir.___
) AS PriorDayIncidents,
ir.NumberOfIncidents AS CurrentDayIncidents,
-- Get the next day's number of incidents
___(ir.___, ___) OVER (
-- Partition by incident type ID
PARTITION BY ir.___
-- Order by incident date
ORDER BY ir.___
) AS NextDayIncidents
FROM dbo.IncidentRollup ir
WHERE
ir.IncidentDate >= '2019-07-02'
AND ir.IncidentDate <= '2019-07-31'
AND ir.IncidentTypeID IN (1, 2)
ORDER BY
ir.IncidentTypeID,
ir.IncidentDate;