-- Выявление уникальных записей среди дубликатов

create temp table _tempPersons as
select min(tpi.PersonInfoID::text)::uuid as PersonInfoID, tpi.AppealToCallCenter, tpi.type_
from vccc.t_person_info tpi
group by tpi.AppealToCallCenter, tpi.type_
having count(*) > 1;

-- Удаление дубликатов

delete from iszl.t_person_info_in personInfoIn
using _tempPersons t, vccc.t_person_info personInfo
where personInfoIn.PersonInfoID = personInfo.PersonInfoID
	and t.AppealToCallCenter = personInfo.AppealToCallCenter
	and t.type_ = personInfo.type_
	and t.PersonInfoID <> personInfo.PersonInfoID;

delete from iszl.t_person_info_z personInfoZ
using _tempPersons t, vccc.t_person_info personInfo
where personInfoZ.PersonInfoID = personInfo.PersonInfoID
	and t.AppealToCallCenter = personInfo.AppealToCallCenter
	and t.type_ = personInfo.type_
	and t.PersonInfoID <> personInfo.PersonInfoID;

delete from vccc.t_person_info personInfo
using _tempPersons t
where t.AppealToCallCenter = personInfo.AppealToCallCenter
	and t.type_ = personInfo.type_
	and t.PersonInfoID <> personInfo.PersonInfoID;

drop table _tempPersons;