使用 ROLLUP 生成汇总
当非度量属性具有层级结构时,ROLLUP 运算符效果最佳。否则,您可能会得到直觉上不合理的聚合层级。
在本场景中,我们希望汇总 IncidentRollup 表中的安全事件总数。管理层希望看到按公历年、公历季度和公历月组合聚合的数据。此外,他们还希望看到"公历年 + 公历季度"的单独汇总行,以及每个公历年的单独汇总行。最后,还需要一行总计。我们可以通过一次操作完成以上所有需求。
本练习是课程的一部分
SQL Server 中的时间序列分析
练习说明
- 通过对每个区间的事件数求和,补全
NumberOfIncidents的定义。 - 完成
GROUP BY段落,并包含WITH ROLLUP运算符。
交互式实操练习
通过完成这段示例代码来试试这个练习。
SELECT
c.CalendarYear,
c.CalendarQuarterName,
c.CalendarMonth,
-- Include the sum of incidents by day over each range
___(ir.___) AS NumberOfIncidents
FROM dbo.IncidentRollup ir
INNER JOIN dbo.Calendar c
ON ir.IncidentDate = c.Date
WHERE
ir.IncidentTypeID = 2
GROUP BY
-- GROUP BY needs to include all non-aggregated columns
c.___,
c.___,
c.___
-- Fill in your grouping operator
WITH ___
ORDER BY
c.CalendarYear,
c.CalendarQuarterName,
c.CalendarMonth;