Вы можете использовать lag()
и накопленную сумму.Но вы уже сделали lag()
, поэтому:
select t.*,
sum(case when date_delta > 30 then 1 else 0 end) over (partition by id order by start_date) + 1 as episode
from t;
Если вам нужно рассчитать также date_delta
:
select t.*,
sum(case when start_date > dateadd(day, 30, prev_date)
then 1 else 0
end) over (partition by id order by start_date) + 1 as episode
from (select t.*,
lag(start_date) over (partition by id order by start_date) as prev_date
from t
) t;