select
cp.contract_id,
c.number,
cp.initial_payment,
cp.current_payment,
cp.payment_frequency,
cp.contribution_ss,
cp.contribution_sr,
cp.contribution_account
from ourpension.contract_params cp
join ourpension.contract c
on c.id = cp.contract_id
where cp.initial_payment is not null
or cp.current_payment is not null
or cp.payment_frequency is not null
or cp.contribution_ss is not null
or cp.contribution_sr is not null
or cp.contribution_account is not null
order by
(
case when cp.initial_payment is not null then 1 else 0 end +
case when cp.current_payment is not null then 1 else 0 end +
case when cp.payment_frequency is not null then 1 else 0 end +
case when cp.contribution_ss is not null then 1 else 0 end +
case when cp.contribution_sr is not null then 1 else 0 end +
case when cp.contribution_account is not null then 1 else 0 end
) desc,
cp.contract_id desc
limit 20;