開始使用免費開始

使用日曆表進行降採樣

管理階層喜歡每週報表,但他們希望看到 2020 年的每一週,而不只是有設施使用記錄的那些週。我們可以用日曆表來解決這個問題:日曆表涵蓋所有週,將它與 dbo.DaySpaVisit 表格連接後就能得到答案。

管理階層也希望看到每個曆週的第一天,因為這能為報表讀者提供重要的背景資訊。

本練習屬於課程

SQL Server 的時間序列分析

檢視課程

練習說明

  • 找出並包含曆年的週次。
  • 在每個群組中納入 c.Date 的最小值,並命名為 FirstDateOfWeek。因為我們是按週分組,這樣做是可行的。
  • Calendar 表與 DaySpaVisit 表連接,依據日曆表的日期與每位日間 SPA 客戶的來訪日期比對。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;
編輯並執行程式碼