查看前後期間
LAG() 和 LEAD() 視窗函式分別讓我們能夠向時間的過去或未來查看。這讓你可以在一個簡潔的查詢中,完成期間對期間的比較。
在這個練習中,你要比較 2019 年 7 月期間,事故種類 1 與 2 的每日資安事件數量,範圍從 7 月 2 日開始到 7 月 31 日結束。
本練習屬於課程
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;