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
Week Start & End Date From Date For Power BI Dax Formula
Here is a
DATEFIRST
agnostic solution:I just encounter a similar case with this one, but the solution here seems not helping me. So I try to figure it out by myself. I work out the week start date only, week end date should be of similar logic.
Expanding on @Tomalak's answer. The formula works for days other than Sunday and Monday but you need to use different values for where the 5 is. A way to arrive at the value you need is
here is a link to the document: https://msdn.microsoft.com/en-us/library/ms181598.aspx
And here is a table that lays it out for you.
But you don't have to remember that table and just the formula, and actually you could use a slightly different one too the main need is to use a value that will make the remainder the correct number of days.
Here is a working example:
This method would be agnostic of the
DATEFIRST
Setting which is what I needed as I am building out a date dimension with multiple week methods included.Let us break the problem down to two parts:
1) Determine the day of week
The
DATEPART(dw, ...)
returns a number, 1...7, relative toDATEFIRST
setting (docs). The following table summarizes the possible values:The last column contains the ideal day-of-week value for Monday to Sunday weeks*. By just looking at the chart we come up with the following equation:
2) Calculate the Monday and Sunday for given date
This is trivial thanks to the day-of-week value. Here is an example:
Output:
* For Sunday to Saturday weeks you need to adjust the equation just a little, like add 1 somewhere.
Not sure how useful this is, but I ended up here from looking for a solution on Netezza SQL and couldn't find one on stack overflow.
For IBM netezza you would use something (for week start mon, week end sun) like:
select next_day (WeddingDate, 'SUN') -6 as WeekStart,
next_day (WeddingDate, 'SUN') as WeekEnd