Wednesday, January 2, 2019

Group data by weeks


Group data by weeks
To group correctly by weeks also between years you need code like this one. Otherwise if you group only by DATEPART, it will aggregate the same week numbers over multiple years.
SELECT
 DATEADD(week, DATEDIFF(week, 0, DateColumn), 0) AS WeekStart
FROM ATable
GROUP BY DATEADD(week, DATEDIFF(week, 0, DateColumn), 0)
To ensure that the start of week is Sunday, you have to 
SET DATEFIRST 7

Details are on


No comments:

Post a Comment