--explain analyze
with line as (SELECT *,
coalesce((LEAD(dt_from) OVER (PARTITION BY line_key ORDER BY dt_from, agreement_version,line_version)), (select max(dt) from elma.mv_dt)) dt_next
FROM
(
  SELECT *,
    MIN(dt_from) OVER (PARTITION BY line_key ORDER BY agreement_version desc,line_version desc) running_min_dt	
  FROM elma.mv_line where siv_is_actual AND probability_pc > 0
) t
WHERE t.dt_from=t.running_min_dt),

base_line as (SELECT *,
coalesce((LEAD(dt_from) OVER (PARTITION BY line_key ORDER BY dt_from, agreement_version,line_version)), (select max(dt) from elma.mv_dt)) dt_next,
max(agreement_version) OVER (PARTITION BY line_key) max_agr_ver
FROM
(
  SELECT *,
    MIN(dt_from) OVER (PARTITION BY line_key, agreement_version ORDER BY agreement_version desc, line_version desc) running_min_dt	
  FROM elma.mv_line where siv_is_actual AND deal_status_id IN ('5','6')
) t
WHERE t.dt_from=t.running_min_dt)

select *
--contract, line_key, dt_from, agreement_version, line_version  
from base_line 
where 
line_key ='0bfd4bfd-641b-444b-9571-b1ab3b00631e'
order by contract, line_key, agreement_version, line_version

--select * from elma.mv_line where line_key='20240530T113112183'; -- кривизна какая то

--select * from elma.deals_services where hash='20240530T113112183';