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?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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
Scott PletcherSenior 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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Ryan SimmonsBusiness Analyst IIIAuthor Commented:
That works thanks!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Sales

From novice to tech pro — start learning today.