Загрузка данных


select
    h.contract_id,
    c.number,
    h.pens_product_id,
    pt.min_term_from,
    pt.min_term_to,
    pt.max_term_from,
    pt.max_term_to,
    pt.payment_type_pl_multiselect_id,
    ms.name as payment_type
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.param_pl pp
    on pp.id = pppp.param_pl_id
join prod_line.table_param_pl_payment_term pt
    on pt.pens_product_param_pl_id = pppp.id
left join prod_line.hb_param_pl_multiselect ms
    on ms.id = pt.payment_type_pl_multiselect_id
where current_timestamp between
      h.begin_date
      and coalesce(h.end_date, 'infinity')
  and pp.brief = 'СрокВыплаты'
  and (
      pt.max_term_to > 0
      or pt.payment_type_pl_multiselect_id is not null
  )
order by
    case
        when pt.max_term_to > 0
         and pt.payment_type_pl_multiselect_id is not null
        then 0
        else 1
    end,
    h.contract_id desc
limit 20;