Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create Week Date Range column based on the service date

I need to create WeekDateRange column based on the ServiceDate column.
Each WeekDateRange value should START with Monday date and END with Sunday date associated with ServiceDate in (mm/dd/yyyy – mm/dd/yyyy) format.

SELECT s.ServiceDate
FROM ServiceInfo AS s
ServiceDate
2022-01-03
2022-01-07
2022-01-15
2022-01-26
2022-01-29
2022-02-01
2022-02-04
2022-02-06
2022-02-07

I tried to use below query, however 2022-02-06 ServiceDate assigns to 02/07/2022 – 02/13/2022 week.

SELECT s.ServiceDate,
       CONCAT(CONVERT(VARCHAR, DATEADD(DAY, 2 - DATEPART(WEEKDAY, 
            s.ServiceDate), CAST(s.ServiceDate AS DATE)), 101), 
            ' - ', CONVERT(VARCHAR, DATEADD(DAY, 8 - DATEPART(WEEKDAY, 
            s.ServiceDate), CAST(s.ServiceDate AS DATE)), 101)) AS 
            WeekDateRange

FROM ServiceInfo AS s

The output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

ServiceDate WeekDateRange
2022-01-03 01/03/2022 – 01/09/2022
2022-01-07 01/03/2022 – 01/09/2022
2022-01-15 01/10/2022 – 01/16/2022
2022-01-26 01/24/2022 – 01/30/2022
2022-01-29 01/24/2022 – 01/30/2022
2022-02-01 01/31/2022 – 02/06/2022
2022-02-04 01/31/2022 – 02/06/2022
2022-02-06 02/07/2022 – 02/13/2022 (Needs to be 01/31/2022 – 02/06/2022)
2022-02-07 02/07/2022 – 02/13/2022

>Solution :

You can use a reference date that is Monday to calculate the difference in days. Perform integer division by 7 and then multiply by 7 will gives you back no of days that starts on Monday

1st Jan, 1900 is a Monday, StartDate :

   DATEADD(DAY, DATEDIFF(DAY, '19000101', s.ServiceDate) / 7 * 7, '19000101') 

For End date, just add 1 week to the difference in days and subtract 1 day from the reference date which is 31 Dec 1899

   DATEADD(DAY, (DATEDIFF(DAY, '19000101', s.ServiceDate) / 7 + 1) * 7, '18991231') 

dbfiddle

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading