views:

2502

answers:

2

I have a query that counts member's wedding dates in the database...

Select 
  Sum(NumberOfBrides) As [Wedding Count], 
  DATEPART( wk, WeddingDate) as [Week Number],
  DATEPART( year, WeddingDate) as [Year]
FROM  MemberWeddingDates
Group By DATEPART( year, WeddingDate), DATEPART( wk, WeddingDate)
Order By Sum(NumberOfBrides) Desc

How do I work out when the start and end of each week represented in the result set?

Select 
      Sum(NumberOfBrides) As [Wedding Count], 
      DATEPART( wk, WeddingDate) as [Week Number],
      DATEPART( year, WeddingDate) as [Year],
      ??? as WeekStart,
      ??? as WeekEnd

    FROM  MemberWeddingDates
    Group By DATEPART( year, WeddingDate), DATEPART( wk, WeddingDate)
    Order By Sum(NumberOfBrides) Desc
+5  A: 

You can find the day of week and do a date add on days to get the start and end dates..

DATEADD(dd, -(DATEPART(dw, WeddingDate)-1), WeddingDate) [WeekStart]

DATEADD(dd, 7-(DATEPART(dw, WeddingDate)), WeddingDate) [WeekEnd]

You probably also want to look at stripping off the time from the date as well though.

Robin Day
Bear in mind that setting `DATEFIRST` to anything other than 7 breaks this.
Tomalak
It won't "break" it, it will use datefirst to set WeekStart = to what DateFirst says the first day of a week is. Your version will always do Monday and Sunday as start and end of a week, not what the server is set to use as start and end of the week
Robin Day
Hm... That's a valid point, +1. :) I'll delete mine, then (Though for being a shot in the foot, it was extremely well aimed. *g*).
Tomalak
Not at all, I think yours is perfectly valid as well as it said Monday and Sunday in the columns. That might have been what was required regardless of any localization settings.
Robin Day
Well, then I undelete it again. I'm not sure who in their right mind would assume anything other than Monday as the start of the week anyway. To start the week on Sunday makes no sense *whatsoever*. :-)
Tomalak
+2  A: 

Here is a DATEFIRST agnostic solution:

SET DATEFIRST 4     /* or use any other weird value to test it */
DECLARE @d DATETIME

SET @d = GETDATE()

SELECT
  @d ThatDate,
  DATEADD(dd, (@@DATEFIRST + 5 + DATEPART(dw, @d)) % 7, @d) Monday,
  DATEADD(dd, 6 - (@@DATEFIRST + 5 + DATEPART(dw, @d)) % 7, @d) Sunday
Tomalak
suppose i better +1 you seeing as you put it back :)
Robin Day
Nah, not required for good karma. But thanks anyway. :-)
Tomalak