TSQL Convert WeekStartDate (Sat-Fri) to Quarter

My weeks start on a Saturday and end on a Friday. In TSQL how can I return the correct quarter?

For instance if I have a weekly sum of sales that is from week '12/30/2017' is there a way to convert that value to Qtr1?
Ryan SimmonsBusiness Analyst IIIAsked:
Who is Participating?
 
Scott PletcherConnect With a Mentor Senior DBACommented:
This calc:
DATEADD(DAY, (DATEDIFF(DAY, 4, week_date) + 6) / 7 * 7, 4)
will go forward to the next Fri (or return the current day if it is Fri).

Then all we have to do is use the standard SQL function on that value to get the "QUARTER":
DATEPART(QUARTER, DATEADD(DAY, (DATEDIFF(DAY, 4, week_date) + 6) / 7 * 7, 4))

For example:

SELECT week_date, DATEPART(QUARTER, DATEADD(DAY, (DATEDIFF(DAY, 4, week_date) + 6) / 7 * 7, 4))
FROM ( VALUES(CAST('12/30/2017' AS date)),('12/29/2017'),('03/29/2018'),('03/30/2018'),('03/31/2018') ) AS data(week_date)
0
 
Dustin SaundersDirector of OperationsCommented:
So, the problem is you want to ignore sales from Saturday & Sunday?  You can just add 2 to the date to push it forward.

Regular:
DECLARE @date DateTime
SET @date = CAST('12/30/2017' AS Datetime)

SELECT DATEPART(QUARTER, @date)

Open in new window

Returns Q4.

DECLARE @date DateTime
SET @date = CAST('12/30/2017' AS Datetime)

SELECT DATEPART(QUARTER, @date+2)

Open in new window

Returns Q1 (pushing forward the date by 2 days).
0
 
Dustin SaundersDirector of OperationsCommented:
If you want to see the END of the week rather than when Monday falls, just add 6 instead of 2.

DECLARE @date DateTime
SET @date = CAST('12/30/2017' AS Datetime)

SELECT DATEPART(QUARTER, @date+6)

Open in new window

0
 
Ryan SimmonsBusiness Analyst IIIAuthor Commented:
That works thanks!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.