Calculating Week Buckets in SQL

I needed to be able to create static week buckets within a single month to be able to group some fact measures by time period. The below accepts a date and then determines the buckets for that month. This will also correctly handle leap years as well. This can be used to join to fact tables for grouping into week buckets.

DECLARE @date DATE = '2020-02-12'
;

WITH weekcalendar AS (

SELECT *
FROM (
         SELECT 1 as WeekNum, DATEFROMPARTS(YEAR(@date),MONTH(@date),1) AS WeekStartDate, DATEFROMPARTS(YEAR(@date),MONTH(@date),7) AS WeekEndDate
UNION SELECT 2 as WeekNum, DATEFROMPARTS(YEAR(@date),MONTH(@date),8) AS WeekStartDate, DATEFROMPARTS(YEAR(@date),MONTH(@date),14) AS WeekEndDate
UNION SELECT 3 as WeekNum, DATEFROMPARTS(YEAR(@date),MONTH(@date),15) AS WeekStartDate, DATEFROMPARTS(YEAR(@date),MONTH(@date),21) AS WeekEndDate
UNION SELECT 4 as WeekNum, DATEFROMPARTS(YEAR(@date),MONTH(@date),22) AS WeekStartDate, DATEFROMPARTS(YEAR(@date),MONTH(@date),28) AS WeekEndDate
UNION SELECT 5 as WeekNum, CASE WHEN DAY(EOMONTH(@date)) <= 28 THEN NULL
                             ELSE DATEFROMPARTS(YEAR(@date),MONTH(@date),29)
                             END AS WeekStartDate
                     ,CASE WHEN DAY(EOMONTH(@date)) > 28 AND DAY(EOMONTH(@date)) = 29 THEN DATEFROMPARTS(YEAR(@date),MONTH(@date),29)
                             WHEN DAY(EOMONTH(@date)) > 28 AND DAY(EOMONTH(@date)) <> 29 THEN DATEFROMPARTS(YEAR(@date),MONTH(@date),DAY(EOMONTH(@date)))
                             END AS WeekEndDate
) q
WHERE [q].[WeekStartDate] IS NOT NULL
)

select * from weekcalendar

Output:


Comments

Popular posts from this blog

Continuously Monitor Folder for New Files with PowerShell as a WindowsService

Unprotect All Excel Sheets for All Workbooks in a Directory

ChromeOS Flow by Hexxeh Install to HDD