insert into ies.T_MEDICAL_EXPERTISE_SCHET(MedicalExpertiseSchetID, MedicalExpertise, Schet, ItemCount)
select newid(), messa.MedicalExpertise, sz.Schet, -1
from ies.T_MEDICAL_EXPERTISE_SCHET_SLUCH_ACCOMPLISHED messa
join ies.T_SCHET_SLUCH_ACCOMPLISHED ssa on (messa.SchetSluchAccomplished = ssa.SchetSluchAccomplishedID)
cross apply(select top 1 ss.SchetZap 
			from ies.T_SCHET_SLUCH ss where ss.SchetSluchAccomplished = ssa.SchetSluchAccomplishedID) aa
join ies.T_SCHET_ZAP sz on (sz.SchetZapID = aa.SchetZap)
where not exists (select * 
				from ies.T_MEDICAL_EXPERTISE_SCHET mes 
				where mes.MedicalExpertise = messa.MedicalExpertise and mes.Schet = sz.Schet)
group by messa.MedicalExpertise, sz.Schet;

update ies.T_MEDICAL_EXPERTISE_ITEM
set MedicalExpertiseSchet = mes.MedicalExpertiseSchetID
	,SchetSluchAccomplished = messa.SchetSluchAccomplished
	,SmoActItem = messa.SmoActItem
from ies.T_MEDICAL_EXPERTISE_SCHET_SLUCH_ACCOMPLISHED messa
join ies.T_SCHET_SLUCH_ACCOMPLISHED ssa on (messa.SchetSluchAccomplished = ssa.SchetSluchAccomplishedID)
cross apply(select top 1 ss.schetzap from ies.T_SCHET_SLUCH ss where ss.SchetSluchAccomplished = ssa.SchetSluchAccomplishedID) aa
join ies.T_SCHET_ZAP sz on (sz.SchetZapID = aa.SchetZap)
join ies.T_MEDICAL_EXPERTISE_SCHET mes on mes.MedicalExpertise = messa.MedicalExpertise and mes.Schet = sz.Schet
where MedicalExpertiseSchetSluchAccomplished = messa.MedicalExpertiseSchetSluchAccomplishedID;

update ies.T_MEDICAL_EXPERTISE_SCHET
set ItemCount = (select count(mei.MedicalExpertiseItemID)
from ies.T_MEDICAL_EXPERTISE_ITEM mei
where mei.MedicalExpertiseSchet = MedicalExpertiseSchetID)
where ItemCount = -1;