Is it possible to put a case statement in a the group by part of a query? Below is an example of a query using the normal Datepart function for the week number, and then the ISO week function to get the correct week number. However in using the ISO function, you have to use a Case Statment, which wont work, as yet, in the Group part. Hope that makes sense.
THIS WORKS
SELECT
datepart(ww,[timestamp]) as 'week'
from dbo.casehistories
group by
datepart(ww,[timestamp])
THIS DOESNT WORK
SELECT
'Week' = case when cast(dbo.ISOweek(dbo.casehistories.[timestamp])as varchar(2)) <10 then cast(datepart(yy,dbo.casehistories.[timestamp])as varchar(4))+ '-' + '0'+ cast(dbo.ISOweek(dbo.casehistories.[timestamp]) as varchar(1)) else cast(datepart(yy,dbo.casehistories.[timestamp])as varchar(4))+ '-' + cast(dbo.ISOweek(dbo.casehistories.[timestamp]) as varchar(2)) end
from dbo.casehistories
group by 'Week' = case when cast(dbo.ISOweek(dbo.casehistories.[timestamp])as varchar(2)) <10 then cast(datepart(yy,dbo.casehistories.[timestamp])as varchar(4))+ '-' + '0'+ cast(dbo.ISOweek(dbo.casehistories.[timestamp]) as varchar(1)) else cast(datepart(yy,dbo.casehistories.[timestamp])as varchar(4))+ '-' + cast(dbo.ISOweek(dbo.casehistories.[timestamp]) as varchar(2)) end
THIS WORKS
SELECT
datepart(ww,[timestamp]) as 'week'
from dbo.casehistories
group by
datepart(ww,[timestamp])
THIS DOESNT WORK
SELECT
'Week' = case when cast(dbo.ISOweek(dbo.casehistories.[timestamp])as varchar(2)) <10 then cast(datepart(yy,dbo.casehistories.[timestamp])as varchar(4))+ '-' + '0'+ cast(dbo.ISOweek(dbo.casehistories.[timestamp]) as varchar(1)) else cast(datepart(yy,dbo.casehistories.[timestamp])as varchar(4))+ '-' + cast(dbo.ISOweek(dbo.casehistories.[timestamp]) as varchar(2)) end
from dbo.casehistories
group by 'Week' = case when cast(dbo.ISOweek(dbo.casehistories.[timestamp])as varchar(2)) <10 then cast(datepart(yy,dbo.casehistories.[timestamp])as varchar(4))+ '-' + '0'+ cast(dbo.ISOweek(dbo.casehistories.[timestamp]) as varchar(1)) else cast(datepart(yy,dbo.casehistories.[timestamp])as varchar(4))+ '-' + cast(dbo.ISOweek(dbo.casehistories.[timestamp]) as varchar(2)) end