Skip to content
Advertisement

How to split lines in SQL table according to rules?

so I have SQL table with many lines. It looks like this (just a couple lines from the top):

Table example

I need to disperse revenue according to project duration equally every 2 months starting first month. So desired result would look like this:

enter image description here

What’s the baest way to achieve this?

Advertisement

Answer

You can use recursive cte :

with cte as (
     select code, finish2 as acc_date, dateadd(month, project_duration, finish2) as end_date
     from table t
     union all
     select code, dateadd(month, 2, acc_date), end_date
     from cte c
     where dateadd(month, 2, acc_date) < end_date
)
select code, acc_date
from cte c;
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement