--select query, * from pg_stat_activity where usename ilike '%sergey%';

with result as (
select distinct person_id, lpu_id from evnpl el where not exists (select 1 from personcard where person_id = el.person_id)
union all
select distinct person_id, lpu_id from evnps es where not exists (select 1 from personcard where person_id = es.person_id)
)
select distinct concat(ps.personsurname_surname,' ',ps.personfirname_firname,' ',ps.personsecname_secname) as "ФИО", 
to_char(ps.personbirthday_birthday, 'dd.MM.yyyy') as "дата рождения", ps.personpolisednum_ednum as "ЕНП",
o.org_name as "МО лечения", 
ua.address_address as "адрес регистрации", pa.address_address as "адрес проживания"

from result r
--join lpu l on l.lpu_id = r.lpu_id
join org o on o.org_id = r.lpu_id
join personstate ps on ps.person_id = r.person_id
left join address ua on ua.address_id = ps.uaddress_id
left join address pa on ua.address_id = ps.paddress_id
