-2

Getting the last 12 weeks from a specific date is easy and can be retrieved by the following command in SQL-server. Its answer is 2014-08-17.

select Dateadd(Week, -12, '2015-08-17')

What I want is to get the last 12 weeks but ending at the end of week. I dont want to see last week of 6, 5, 4, 3, 2, 1 days. Please help.

Dr. Mian
  • 3,334
  • 10
  • 45
  • 69

1 Answers1

1

The easy way is to break it down to pieces:

First, Find the date of the last Sunday (thanks to Andriy M)

Then all you have to do is use DateAdd(week, -12, @LastSunday).

Here is the full script:

DECLARE @Date datetime = GETDATE(),
        @LastSunday datetime,
        @TargetDate datetime


SET @LastSunday = DATEADD(day,
                          -1 - (DATEPART(dw, @Date) + @@DATEFIRST - 2) % 7,
                          @Date
                          )

SET @TargetDate = DATEADD(week, -12, @LastSunday)

Play with it your self in this sql fiddle..

Community
  • 1
  • 1
Zohar Peled
  • 79,642
  • 10
  • 69
  • 121
  • One problem is that I also want to show data of the current week. Any idea? – Dr. Mian Aug 18 '15 at 09:36
  • why is that a problem? just get the data between `@TargetDate` (12 weeks ago) and `@NextSaturday` (If you already know how to get last Sunday, surly you can figure out how to get next Saturday...) – Zohar Peled Aug 18 '15 at 13:58