--show work_mem;
--explain (analyze, verbose, buffers)
-- компоненты можно преагрегировать
select dayscale.dt, w.siv_uid, line_key
--,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 * from elma.mv_line i where ) w on dayscale.dt >= w.dt_from

elma.mv_line w on (dayscale.dt >= w.dt_from AND w.siv_uid = 
	(select siv_uid from elma.mv_line i 
	where i.line_key = w.line_key AND dayscale.dt >= i.dt_from 
	order by line_version desc, agreement_version desc limit 1)
)
--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-01-10'
--AND w.line_key='20241009T112450304'
--AND b.deal_status_id IN ('5','6')
--group by dayscale.dt
order by dayscale.dt
--limit 100