Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server Select last 4 weeks from now and same period from last year only

I have tried searching for a soln to this but have been unable yet to find one.

I need to select the last 4 weeks of data from todays date which is not the issue as I just do a date >= Dateadd(mm, -1, getdate()). However I also want the same 4 weeks of data from the previous year. But I dont want (for example) June 1-30 2010 and June 1-30 2011, I would need

June 30th (thursday) 2011 and 4 weeks prior AND July 1st and four weeks prior as july 1st was the thursday in the same week from the prev year.

so 8 weeks of data would be returned.

Thanks for the help!

like image 710
CAR Avatar asked Jul 05 '11 14:07

CAR


1 Answers

You can use some more DATEADD() goodness to go back to the previous year:

where theDate >= DATEADD(mm, -1, GETDATE())    
OR
    (theDate <= DATEADD(week,-52,convert(datetime,GETDATE()))
     and
     theDate >= DATEADD(mm,-1,DATEADD(week,-52,convert(datetime,GETDATE()))))

Subtracting 52 weeks from 6/30/2011 returns 7/1/2010 as you requested... Then using your original subtraction of 1 month from there for the lower bound.

You could also switch the whole thing to use weeks...

where theDate >= DATEADD(week, -4, GETDATE())    
OR
    (theDate <= DATEADD(week,-52,convert(datetime,GETDATE()))
     and
     theDate >= DATEADD(week,-56,convert(datetime,GETDATE())))
like image 50
Fosco Avatar answered Oct 19 '22 03:10

Fosco