There is a datepart iso_week returning the iso_week for a selected day.
SELECT DATEPART(iso_week, getdate())
This will return the european standard for week current. It is not nessasarily the same as week.
Here comes the tricky part:
SELECT DATEPART(iso_week, '2011-01-01')
Returns
52
so it belongs to last year In order to group by year and iso_week, I need to consider that iso_week is not from the same year.
Iso_week starts on monday and belongs to the year where most days overlap. So 4 days in 2010 and 3 days in 2011, the week is 52 and all days belong to iso_year 2010. However TSQL doesn't have the detepart iso_year.
declare @t table(col1 datetime)
insert @t
ALL SELECT '2010-12-28'
UNION ALL SELECT '2010-12-29'
UNION ALL SELECT '2010-12-30'
UNION ALL SELECT '2010-12-31'
UNION ALL SELECT '2011-01-01'
UNION ALL SELECT '2011-01-02'
--UNION ALL SELECT '2011-01-03' Stackexchange is bugged and can't handle this line showing 53
UNION ALL SELECT '2011-01-04'
I need something like (iso_year doesn't exist):
SELECT DATEPART(ISO_WEEK, col1) WEEK, DATEPART(iso_YEAR, col1) YEAR, COUNT(*) COUNT
FROM @t
GROUP BY DATEPART(ISO_WEEK, col1), DATEPART(iso_YEAR, col1)
ORDER BY 2,1
Expected result
WEEK YEAR COUNT
52 2010 6
1 2011 2