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

SQL Server – Breakdown date period

I want to create a query that breakdowns a date period into 10 days sub-periods

So a period of 2022-04-15 to 2022-05-01 should be broken into

2022-04-15 2022-04-24
2022-04-25 2022-05-01 

The period could be one day (2022-04-15 to 2022-04-15) or even years

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

Any help appreciated

Thank you

>Solution :

A Tally would be a much more performant approach:

DECLARE @Start date = '20220415',
       @End date = '20220501',
       @Days int = 10;

WITH N AS (
    SELECT N
    FROM (VALUES(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL))N(N)),
Tally AS(
    SELECT 0 AS I
    UNION ALL
    SELECT TOP (DATEDIFF(DAY,@Start,@End)/@Days)
           ROW_NUMBER() OVER (ORDER BY (SELECT NULL))
    FROM N N1, N N2, N N3, N N4) --Up to 1,000 rows. Add more cross joins for more rows
SELECT DATEADD(DAY, T.I*@Days,@Start),
       CASE WHEN DATEADD(DAY, ((T.I+1)*@Days)-1,@Start) > @End THEN @END ELSE DATEADD(DAY, ((T.I+1)*@Days)-1,@Start) END
FROM Tally T;
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