Using the syntax
dateadd(week, datediff(week, 0, CURRENT_TIMESTAMP),0)
to group data by week it appears that the last day of the week gets put into the following week.
In a simple example
print dateadd(week, datediff(week, 0, '27 jan 2012 00:00'),0)
print dateadd(week, datediff(week, 0, '28 jan 2012 00:00'),0)
print dateadd(week, datediff(week, 0, '29 jan 2012 00:00'),0)
print dateadd(week, datediff(week, 0, '30 jan 2012 00:00'),0)
print dateadd(week, datediff(week, 0, '31 jan 2012 00:00'),0)
I would expect to return
Jan 23 2012 12:00AM
Jan 23 2012 12:00AM
Jan 23 2012 12:00AM
Jan 30 2012 12:00AM
Jan 30 2012 12:00AM
or
Jan 22 2012 12:00AM
Jan 22 2012 12:00AM
Jan 29 2012 12:00AM
Jan 29 2012 12:00AM
Jan 29 2012 12:00AM
depending on DATEFIRST settings I guess
however it returns
Jan 23 2012 12:00AM
Jan 23 2012 12:00AM
Jan 30 2012 12:00AM
Jan 30 2012 12:00AM
Jan 30 2012 12:00AM
i.e. the 29 January is in the week of 30th January not 23rd January or 30th January as expected.
I’m clearly missing something but can’t think what it might be.
This is correct.
No matter what
@@DATEFIRSTis, there is always the same number of whole weeks between now and 01 Jan 1900. As@@DATEFIRSTchanges, it affects both “start” and “end” week.DATEADD then just adds 7 day periods because it ignores @@DATEFIRST
You can force it by choosing the DATEADD base
Example: 01 Jan 1900 is a Monday.
You want Sunday? Then base to 31 Dec 1899
You want Tuesday? Then base to 02 Jan 1900