--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 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 dayscale.dt
,sum (c.cost/dayscale.monthdays*w.probability_pc/100) 
,max(w.dt_from),max(b.dt_from), max(w.probability_pc)
,count(*) 
--,w.line_key, w.dt_from, w.dt_to, w.line_version, w.agreement_version, w.deal_status_id, w.contract, w.probability_pc
from 
elma.mv_dt dayscale  
left outer join line w on (dayscale.dt >=w.dt_from AND dayscale.dt < w.dt_next)
join elma.mv_component c on (w.siv_uid=c.siv_uid)


left outer join base_line b on 
(b.agreement_is_actual AND w.line_key = b.line_key AND dayscale.dt >= b.dt_from AND dayscale.dt < b.dt_next
AND b.agreement_version = (select max(agreement_version) from base_line i where i.line_key = w.line_key AND dayscale.dt >= i.dt_from AND dayscale.dt < i.dt_next AND (w.agreement_version>i.agreement_version OR w.agreement_version IS NULL)))


where 1=1
--AND dayscale.dt between '2025-01-01' AND '2025-02-10'
AND w.line_key='0bfd4bfd-641b-444b-9571-b1ab3b00631e'

group by dayscale.dt
order by dayscale.dt

-- select * from elma.mv_line where line_key='0bfd4bfd-641b-444b-9571-b1ab3b00631e' AND probability_pc=100 order by agreement_version, line_version

