Question

I am building an SSRS report.

In the report, the week always runs from Monday - Sunday.
And I want to find out the START and END dates of prior two weeks.

For example,

If current date = Jan 1, 2011
-- current week = Dec 27, 2010 to Jan 2, 2011
-- previous week = Dec 20, 2010 to Dec 26, 2010

I have tried the following, but seems like it fails when when current day = Sunday

DECLARE @DT DATETIME
DECLARE @Offset INT
DECLARE @CM DATETIME
DECLARE @PM DATETIME
DECLARE @PS DATETIME

--SET @DT = GETDATE()
SET @DT = '11/14/2010' -- Monday
SET @Offset = (DATEPART(WEEKDAY, @DT) - 2) * -1
SET @CM = DATEADD(DAY, @Offset, @DT)
SET @PM = DATEADD(DAY, -7, @CM)
SET @PS = DATEADD(DAY, -1, @CM)

SELECT @Offset AS Offset, @DT AS Date, @CM AS Monday, @PM AS [Previous Monday], @PS AS [Previous Sunday], DATEPART(WK, @PM) AS Week

How can I fix it?

Was it helpful?

Solution

Not sure if this is the most elegant solution but you could do a case statement with your @offset like this:

SET @offset = CASE WHEN DATEPART(weekday, @today) >= 2
                  THEN -(DATEPART(weekday, @today) - 2)
                  ELSE -(DATEPART(weekday, @today) + 5)
               END

I believe it works for all cases.

OTHER TIPS

Add a [Calendar] table to your DB with all the dates you need precalculated. You can then include fields with the day name, number, holiday etc. and simply look up the values you need.

It's much simpler than playing with DATEADD

A useful article on calendar tables: Why should I consider using an auxiliary calendar table?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top