使用 SUM() 计算累计总计
窗口函数的一大用处是计算累计总计:在一段时间内对某个数值进行持续累加。在这里,我们希望使用窗口函数,计算 2019 年 7 月按日期和事件类型每天发生了多少起事件,并按事件类型给出事件总数的累计值。使用一个查询中的窗口函数就能解决这个问题。
本练习是课程的一部分
SQL Server 中的时间序列分析
练习说明
- 填入正确的窗口函数。
- 在窗口函数中补全
PARTITION BY子句,按事件类型 ID 分区。 - 在窗口函数中补全
ORDER BY子句,按事件日期(默认升序)排序。
交互式实操练习
通过完成这段示例代码来试试这个练习。
SELECT
ir.IncidentDate,
ir.IncidentTypeID,
ir.NumberOfIncidents,
-- Get the total number of incidents
___(ir.NumberOfIncidents) OVER (
-- Do this for each incident type ID
PARTITION BY ir.___
-- Sort by the incident date
ORDER BY ir.___
) AS NumberOfIncidents
FROM dbo.IncidentRollup ir
INNER JOIN dbo.Calendar c
ON ir.IncidentDate = c.Date
WHERE
c.CalendarYear = 2019
AND c.CalendarMonth = 7
AND ir.IncidentTypeID IN (1, 2)
ORDER BY
ir.IncidentTypeID,
ir.IncidentDate;