INSERT INTO @blah (ID, Date)
VALUES (123, '11/12/2012')
VALUES (124, '11/30/2012')
VALUES (125, '11/28/2012')
VALUES (126, '12/1/2012')
VALUES (127, '12/30/2012')
VALUES (128, '12/25/2012')
VALUES (129, '12/26/2012')
I want to get rows where the date is the last week of the respective month going back two months. This month is Jan 2013, so i want the last week of Dec 2012 and Nov 2012.
The ultimate option would be the last full week of a month example: dec 2012 = 12/23-12/29 but for now ill take the last 7 days of the month.
I know how to get the last two months but unsure how to get the last week of the respective month..
select
*
from
@blah
where
dateDiff(month,date,getdate()) < 2 ---only look at the last two months
This meets the stated requirement (last full week of previous two months):
To make this more dynamic (you should do your best to state these requirements FIRST, not after people have put in a bunch of work), you can say:
Please don't let anyone convince you to use
LIKE
for date comparison queries. Not only does this kill sargability (meaning no index can be used), but, for a problem like this, how do you determine what string patterns to match? The difficulty is not in constructing theWHERE
clause, but rather what to fill in for the magic(Your Dates go here)
placeholder. And when you do find the range of dates, do you really want 14 individualLIKE
expressions? I wouldn't.This works in Oracle - may give you some ideas and hopefully helps:
This is somewhat dependent on your sql server. This example is similar to Oracle. Each server has its own functions, like SYSDATE and NOW.
For example.