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

Generate repeating data based on date range

I want to create a view with result like this in SQL Server,

from data table with date range per row (start date – end date), can generate repeating data based on a date range to get the number of months for repeating data (by displaying the date of the beginning of each month).

data table

name Debt Start Date End Date
A 100 2022-01-24 2022-03-31
B 50 2022-01-17 2022-02-28
C 80 2023-02-06 2023-02-28

result view

name Debt Checkpoint Date End Date
A 100 2023-01-01 2022-03-31
A 100 2023-02-01 2022-03-31
A 100 2023-03-01 2022-03-31
B 50 2023-01-01 2022-02-28
B 50 2023-02-01 2022-02-28
C 80 2023-02-01 2023-02-28

Can it be creating using View without creating a function?

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

>Solution :

I would approach this using a recursive CTE:

WITH cte AS (
    SELECT name, debt, DATETRUNC(month, start_date) AS start_date, end_date
    FROM mytable
    UNION ALL
    SELECT m.name, m.debt, DATEADD(month, 1, c.start_date), m.end_date
    FROM mytable m
    JOIN cte c ON c.name = m.name
                  AND DATEADD(month,1,c.start_date) < m.end_date
)
SELECT *
FROM cte
ORDER BY name, start_date;

Results :

name    debt    start_date  end_date
A       100     2022-01-01  2022-03-31
A       100     2022-02-01  2022-03-31
A       100     2022-03-01  2022-03-31
B       50      2022-01-01  2022-02-28
B       50      2022-02-01  2022-02-28
C       80      2023-02-01  2023-02-28

Demo here

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