update di
	set di.LastVisit = isnull(re.VisitID, di.VisitID)
	,	di.VisitCount = isnull(re.VisitCount, 1)
	from AKUZ.T_DOCTOR_INSPECTION di
	outer apply
	(
		select top (1) t1.VisitID, count(*) over (partition by t1.DoctorInspection) as VisitCount 
		from AKUZ.T_DOCTOR_INSPECTION_RE t1 with(nolock) 
		inner join AKUZ.T_VISIT t2 with(nolock) on t1.VisitID = t2.VisitID and t1.DoctorInspection = di.VisitID
		order by t2.VisitDate desc
	) re
GO