I have to collect all the rows in a table where they were inserted on a Monday for the last 3 three months. How would I write the WHERE clause date to get those results?
WHERE Date = (wk, DATEDIFF(wk,0,GETDATE()), 0)
That will select everything from Monday of the current week, but what I am having a problem with is selecting a range of Mondays going back three months.
thanks!
So this is the WHERE clause I ended up with that works well for me….
where Datestamp > dateadd(month, -3, getdate())
AND datepart(weekday, Datestamp) = datepart(weekday, DATEADD(wk, DATEDIFF(wk,0,GETDATE()), 0))
I changed only the part where we enter the day of the week that starts on Monday I added this…
DATEADD(wk, DATEDIFF(wk,0,GETDATE()), 0)
These are two separate conditions; no need to compress them into one.
Note: run a test on your machine to see which value you get for
datepart(weekday, @AMondayDate). On some systems Monday is 1, on others is 2; it depends on the DATEFIRST configuration.Update:
Thanks to ErikE for the clever trick that overcomes the weekday numbers issue: