select * from elma.deals;
select * from elma.aggrements;
select * from elma.additional_agreements;
select * from elma.deals_services limit 100;
select * from elma.service_parametrs limit 100; --не имеет реляционной связи со строкой, только обратный массив. 
-- О ужас, сюда запихнута ссылка на сделку. И код и цена
-- по какому признаку мы узнаем, что параметр это зеркало сервиса (или это не нужно впр)


select deal,count(*) from elma.deals_services 
where is_actual
group by deal having count(*) >10 limit 100;

select user_description, hash, version, is_actual, * 
from elma.deals_services 
where deal='{01907e04-8600-508d-874a-d0ebc5c14b44}'
order by __name, version;

select deal,version, count(*) from elma.deals_services where is_actual group by deal, version having count(*)>10

select user_description, hash, version, is_actual, * 
from elma.deals_services 
where deal='{019685f8-4430-7a48-84c0-8968ede1fcad}'
order by deal, version;

select deal,version, count(*) from elma.deals_services where is_actual group by deal, version having count(distinct version)>0
Значит смотреть по допнику!
Проверить, у is_actual допник должен быть?

with 
component as (
select siv.__id as siv_uid, siv.discount, siv.cnt as quantity, siv.type as pricing_model_id 
,siv.hash as line_key, siv.user_description, siv.is_actual as siv_is_actual
,siv.version, GREATEST(siv.date_nop,d."_plannedDueDate") as df_from, date_end as dt_to, is_easy as is_simple, siv.cnt as quantity
, a.__id as agreement_uid, a.contract_uid, a.is_actual as agreement_is_actual, a.deal_uid
,d."_plannedDueDate", d.__name as deal
,p.code, p.price, p.cnt as param_quantity, p.discount as param_discount, p.name as sku
from elma.deals_services siv
join elma.additional_agreements a on (a.__id = ANY(siv.additional_agreement)) 
join elma.deals d on (d.__id = ANY(siv.deal)) 
join elma.service_parametrs p on (p.__id = ANY (siv.params))
join elma.aggrements c on (a.contract_uid = c.__id)
),
maxver as (
select max(version) as ver, count(*) as cnt /*, line_key, contract_uid*/ from component /*group by line_key, contract_uid*/
)
select * from maxver
limit 100 offset 10000

--where NOT is_simple