select
h.contract_id,
c.number,
h.pens_product_id,
count(*) as coeff_count
from ourpension.contract_product_history h
join ourpension.contract c
on c.id = h.contract_id
join prod_line.pens_product_param_pl pppp
on pppp.pens_product_id = h.pens_product_id
join prod_line.table_param_pl_redemption_coeff tpprc
on tpprc.pens_product_param_pl_id = pppp.id
and tpprc.contract_id is null
where current_timestamp between
h.begin_date
and coalesce(h.end_date, 'infinity')
group by
h.contract_id,
c.number,
h.pens_product_id
order by
coeff_count desc,
h.contract_id desc
limit 20;