and not exists (
select 1
from ourpension.year_tax_deduction td2
left join ourpension.application_termination_contract atc2
on atc2.id = td2.application_termination_contract_id
left join ourpension.application_termination_contract_data atcd2
on atcd2.application_termination_contract_id = atc2.id
left join ourpension.sharer sh2
on sh2.id = atcd2.sharer_id
left join ourpension.contract contract2
on contract2.id = sh2.contract_id
where td2.type != 'NONE'
and contract2.number = contract.number
and (
td2.year > td.year
or (
td2.year = td.year
and td2.id > td.id
)
)
)