Here is a DDL to create a table with the dates that I'm working withcreate table [DateTest]( CalendarYear int, DateValue datetime)insert into DateTest (CalendarYear, DateValue)values ('2015', '12/27/2015')insert into DateTest (CalendarYear, DateValue)values ('2015', '12/28/2015')insert into DateTest (CalendarYear, DateValue)values ('2015', '12/29/2015')insert into DateTest (CalendarYear, DateValue)values ('2015', '12/30/2015')insert into DateTest (CalendarYear, DateValue)values ('2015', '12/31/2015')insert into DateTest (CalendarYear, DateValue)values ('2016', '01/01/2016')insert into DateTest (CalendarYear, DateValue)values ('2016', '01/02/2016')insert into DateTest (CalendarYear, DateValue)values ('2016', '01/03/2016')insert into DateTest (CalendarYear, DateValue)values ('2016', '01/04/2016')When you run the following SQL statementselect CalendarYear,case when datepart(dw, [DateValue]) = 1 then convert(int, convert(char(4), datepart(year, DATEADD(wk, DATEDIFF(wk,0,([DateValue] -1)), 0))) + replicate('0', 2) - len(datepart(week, DATEADD(wk, DATEDIFF(wk,0,([DateValue] -1)), 0))) + convert(char(4), datepart(week, DATEADD(wk, DATEDIFF(wk,0,([DateValue] -1)),0)))) else convert(int, convert(char(4), datepart(year, DATEADD(wk, DATEDIFF(wk,0,[DateValue]), 0))) + replicate('0', 2) - len(datepart(week, DATEADD(wk, DATEDIFF(wk,0,[DateValue]), 0))) + convert(char(4), datepart(week, DATEADD(wk, DATEDIFF(wk,0,[DateValue]), 0)))) end NewWeek , datepart(dw,[DateValue])from DateTestwhere DateValue between '12/28/2015' and '01/03/2016'You will get results like this CalendarYear NewWeek DayOfWeek------------ ----------- -----------2015 201551 22015 201551 32015 201551 42015 201551 52016 201551 62016 201551 72016 201551 1As you can see the calendar year is showing 2016 for the January dates, however, I need it to show 2015. The reason for needing it to be 2015 is that per my fiscal calendar they are 2015 dates. The only time I need this to happen (as I didn't provide future dates) is when the week traverses starts in December and ends in January. My fiscal calendar week is Monday to Sunday. Any help is greatly appreciated
↧