If you can assume that all your dates are covered within the data then you can use min
and max
, otherwise you'll need to calculate them:
dateadd(dd, -datepart(dw, min(ApplicationDate)) + 1) as StartOfWeek,
dateadd(dd, -datepart(dw, min(ApplicationDate)) + 7) as EndOfWeek
I'm assuming the your datefirst
settings corresponds to the logical week you want to use as you're already relying on that. Also double-check the documentation for datepart(wk, ...)
to confirm it does what you're expecting especially for dates around the beginning and end of the year. (See the accepted answer at Difficulties comprehending ISO_week and week in Microsoft SQL, what's happening exactly?)
Some people prefer to avoid the old datepart codes so here are the equivalents:
dateadd(day, -datepart(weekday, min(ApplicationDate)) + 1) as StartOfWeek,
dateadd(day, -datepart(weekday, min(ApplicationDate)) + 7) as EndOfWeek
You may find it better to group on a count of the number of weeks since a fixed reference point. January 1, 2012 happened to be a Sunday so I'll use it. All of the same logic above will still work and it doesn't really matter if any of your data falls before that date since the value of the expression will just be a negative number:
group by datediff(wk, '20120101', ApplicationDate)