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

Viewed 45165

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!

3 Answers

Last four weeks sales data:

with cte as (
    select case when row_number() OVER (ORDER BY DATEPART(wk,CreatedDate) DESC) = 2 then 'last 1st Week'
                when row_number() OVER (ORDER BY DATEPART(wk,CreatedDate) DESC) = 3 then 'last 2nd Week'
                when row_number() OVER (ORDER BY DATEPART(wk,CreatedDate) DESC) = 4 then 'last 3rd Week'
                when row_number() OVER (ORDER BY DATEPART(wk,CreatedDate) DESC) = 5 then 'last 4th Week'  
                else 'last 5th plusweek'
           end as weeks,
    sum(amt) as week_wise_sale,
    row_number() OVER (ORDER BY DATEPART(wk,CreatedDate) DESC) AS [row number]
    from samt 
    group by DATEPART(wk,CreatedDate)
) select * from cte where [ROW NUMBER] > 1
Related