--explain analyze
select dayscale.dt
,sum (c.cost/dayscale.monthdays), 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 (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
) t
WHERE t.dt_from=t.running_min_dt) 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 elma.mv_line b on 
(w.line_key = b.line_key AND dayscale.dt >= b.dt_from 
AND b.agreement_version = (select max(agreement_version) from elma.mv_line i where i.line_key = w.line_key AND dayscale.dt >= i.dt_from AND (w.agreement_version>i.agreement_version OR w.agreement_version IS NULL)))

where dayscale.dt between '2025-01-01' AND '2025-03-10'
--AND w.line_key='20241009T112450304'
--AND b.deal_status_id IN ('5','6')
group by dayscale.dt
order by dayscale.dt

