Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the week start date and week end date from week number

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 
like image 653
digiguru Avatar asked Aug 12 '09 16:08

digiguru


People also ask

How do you calculate weeks from start and end date?

Change the start and end dates below to calculate the number of weeks between the dates. To calculate the number of weeks between two dates, start by counting the number of days between the start and end date. Then, divide that number by 7 days per week.

How do you find the start of the week from the date?

Note: This formula =A2-WEEKDAY(A2,2)+1 will return Monday as the beginning of week based on the given date. Select a blank cell you will return the beginning of week, and enter the formula =A2-MOD(A2-2,7) (A2 is the cell with given date) into it, and then drag the Fill Handle to the range as you need.


2 Answers

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.

like image 53
Robin Day Avatar answered Sep 26 '22 20:09

Robin Day


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, 0 - (@@DATEFIRST + 5 + DATEPART(dw, @d)) % 7, @d) Monday,   DATEADD(dd, 6 - (@@DATEFIRST + 5 + DATEPART(dw, @d)) % 7, @d) Sunday 
like image 21
Tomalak Avatar answered Sep 24 '22 20:09

Tomalak