with
status(status, status_id, probability_pc) as (VALUES
('Закрыта неуспешно',7,0),('Закрыта успешно',6,100),('Договор подписан',5,100),('Договор на подписании',15,90),('Договор на согласовании',12,70),
('Тестирование',8,50),('Отправлено ТКП',10,20),('Внутреннее согласование',37,10),('Проработка решения',4,10),('Сбор потребностей',1,0)
)

,line_expanded as
(
SELECT
siv.__id as siv_uid ,
siv.discount ,
siv.type as line_pricing_model_id ,
siv.hash as line_key ,
siv.is_actual as siv_is_actual ,
siv.version::numeric as line_version ,
siv.modifier_code ,
siv.abstractive_service_code ,
d.__index as deal_index ,
d._companies ,
a.index as agreement_version ,
siv.date_nop::date as dt_from ,
siv.date_end::date as dt_to ,
siv.is_easy as is_simple ,
siv.cnt ,
s.probability_pc ,
a.__id as additional_agreement_uid ,
a.__name as additional_agreement ,
a.contract_uid ,
a.is_actual as additional_agreement_is_actual ,
a.deal_uid ,
d.__name as deal ,
d.__status_status as deal_status_id ,
siv.user_description 
--,unnest(siv.params) as param_id
FROM elma.deals_services siv
JOIN elma.deals d on (d.__id = ANY(siv.deal))
JOIN status s on (d.__status_status=s.status_id)
LEFT JOIN elma.additional_agreements a on (a.__id = ANY(siv.additional_agreement))
WHERE
siv.is_actual
AND siv."__deletedAt" IS NULL
and d."__deletedAt" IS NULL
and a."__deletedAt" IS NULL
and s.probability_pc >= 50
and siv.type IN (2,3)
),
component as
(
SELECT
cnt ,
code ,
__id,
price,
ed_izm,
discount,
name
FROM
elma.service_parametrs
where
"__deletedAt" IS NULL
),
stair as
(
select
*
FROM
(
SELECT
*,
MIN(dt_from) OVER (PARTITION BY line_key ORDER BY deal_index desc) running_min_dt
FROM
line_expanded
WHERE
probability_pc > 0
) t
WHERE
t.dt_from = t.running_min_dt
AND ( t.dt_to > CURRENT_TIMESTAMP OR t.dt_to IS NULL )
)

SELECT
d.siv_uid
,d.deal
,d.user_description
,d.discount
,d.cnt
,d.modifier_code
,d.abstractive_service_code
,d.siv_is_actual --
,d.line_pricing_model_id --
,d.line_key
,d.deal_index --
,d.dt_from --
,d.dt_to --
,d.is_simple --
--,d.params::text
,d.additional_agreement_uid
,d.additional_agreement
/*,p.price
,p.cnt as p_cnt
,p.ed_izm
,p.code
,p.discount as p_discount
,p.__id as p_uid
,p.name*/
,s.probability_pc
,s.status_id
,s.status
,d.deal_index 
,d.deal_uid 
FROM stair d
--left outer join component p on (d.param_id=p.__id)
JOIN status s on (d.deal_status_id=s.status_id)
where d._companies='019503f2-5774-7768-b5c9-566a71daedaa'