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
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With