1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
|
with projection as (
select itv_item, itv_debut as dt, +1 as direction
from t_interval_itv
union all
select itv_item, itv_fin as dt, -1 as direction
from t_interval_itv
),
sumsumsum as (
select itv_item, dt,
sum(direction) over (partition by itv_item order by dt, direction desc) as cnt,
coalesce(sum(direction) over (partition by itv_item order by dt, direction desc rows between unbounded preceding and 1 preceding),0) as lag_cnt
from projection
),
make_order as (
select itv_item, dt, 0 as pos
from sumsumsum
where cnt > 0 and lag_cnt = 0
union all
select itv_item, dt, 1 as pos
from sumsumsum
where cnt = 0 and lag_cnt >0
),
make_interval as (
select itv_item, dt as itv_debut,
lead(dt) over (partition by itv_item order by dt) as itv_fin,
pos
from make_order
)
select itv_item, itv_debut, itv_fin
from make_interval
where pos = 0 |
Partager