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

select min(tpi.PersonInfoID) as PersonInfoID, tpi.AppealToCallCenter, tpi.type_
into #tempPersons
from VCCC.T_PERSON_INFO tpi
group by tpi.AppealToCallCenter, tpi.type_
having count(*) > 1;

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

delete personInfoIn
from #tempPersons temp
join VCCC.T_PERSON_INFO personInfo
	on temp.AppealToCallCenter = personInfo.AppealToCallCenter
	and temp.type_ = personInfo.type_
join ISZL.T_PERSON_INFO_IN personInfoIn
	on personInfoIn.PersonInfoID = personInfo.PersonInfoID
where temp.PersonInfoID <> personInfo.PersonInfoID;

delete personInfoZ
from #tempPersons temp
join VCCC.T_PERSON_INFO personInfo
	on temp.AppealToCallCenter = personInfo.AppealToCallCenter
	and temp.type_ = personInfo.type_
join ISZL.T_PERSON_INFO_Z personInfoZ
	on personInfoZ.PersonInfoID = personInfo.PersonInfoID
where temp.PersonInfoID <> personInfo.PersonInfoID;

delete personInfo
from #tempPersons temp
join VCCC.T_PERSON_INFO personInfo
	on temp.AppealToCallCenter = personInfo.AppealToCallCenter
	and temp.type_ = personInfo.type_
where temp.PersonInfoID <> personInfo.PersonInfoID;

drop table #tempPersons;