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

DB2 SQL forecast generation based giving as parameters end date

I have a table with activities. The columns are: activityId, nextDate, frequency.
The frequency is in months.
I need a query that will generate all the dates at which the activity will take place based on frequency (in months).
I am using DB2.

Activities table:

activityId nextDate frequency
1 03/01/2024 2

Giving parameter: 12/31/2024

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

Output needed:

activityId date
1 03/01/2024
1 05/01/2024
1 07/01/2024
1 09/01/2024
1 11/01/2024

>Solution :

You can do it with a recursive CTE

with activities (activityId, nextDate, frequency) as (
  values (1, date '2024-03-01', 2)
),
activities_this_year (activityId, firstDate, number, nextDate, frequency) as (
  select activityId, nextDate as firstDate, 1, nextDate, frequency from activities
  union all
  select
    activityId,
    firstDate,
    number + 1,
    nextDate + frequency month,
    frequency
  from activities_this_year
  where nextDate + frequency month < this_year(current date) + 1 year
)
select activityId, nextDate from activities_this_year order by activityId, nextDate

ACTIVITYID NEXTDATE
1 2024-03-01
1 2024-05-01
1 2024-07-01
1 2024-09-01
1 2024-11-01

fiddle

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