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,
        1 + 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;