开始使用免费开始使用

使用日历表进行下采样

管理层认可按周的报告,但他们希望看到 2020 年的每一周,而不仅是有设施使用记录的那些周。我们可以使用日历表来解决这个问题:日历表包含所有周,因此我们可以将其与 dbo.DaySpaVisit 表进行连接来找到答案。

管理层还希望看到每个公历周的第一天,这能为报告查看者提供重要的背景信息。

本练习是课程的一部分

SQL Server 中的时间序列分析

查看课程

练习说明

  • 找出并包含公历周。
  • 在每个分组中包含 c.Date 的最小值,命名为 FirstDateOfWeek。这是可行的,因为我们按周进行分组。
  • 基于日历表的日期与每位日间水疗客户的来访日期,将 Calendar 表与 DaySpaVisit 表连接。CustomerVisitStart 是包含时间的 DATETIME2,因此直接连接只会包含恰好在午夜开始的访问。
  • 按公历周进行分组。

交互式实操练习

通过完成这段示例代码来试试这个练习。

SELECT
	-- Determine the week of the calendar year
	c.___,
	-- Determine the earliest DATE in this group
    -- This is NOT the DayOfWeek column
	MIN(c.___) AS FirstDateOfWeek,
	ISNULL(SUM(dsv.AmenityUseInMinutes), 0) AS AmenityUseInMinutes,
	ISNULL(MAX(dsv.CustomerID), 0) AS HighestCustomerID,
	COUNT(dsv.CustomerID) AS NumberOfAttendees
FROM dbo.Calendar c
	LEFT OUTER JOIN dbo.DaySpaVisit dsv
		-- Connect dbo.Calendar with dbo.DaySpaVisit
		-- To join on CustomerVisitStart, we need to turn 
        -- it into a DATE type
		ON c.Date = CAST(dsv.___ AS ___)
WHERE
	c.CalendarYear = 2020
GROUP BY
	-- When we use aggregation functions like SUM or COUNT,
    -- we need to GROUP BY the non-aggregated columns
	c.___
ORDER BY
	c.CalendarWeekOfYear;
编辑并运行代码