UPDATE akuz.t_doctor_inspection di
SET lastvisit  = COALESCE(lv.visitid, di.visitid),
    visitcount = COALESCE(lv.visitcount, 1)
FROM akuz.t_doctor_inspection tdi
LEFT JOIN LATERAL
    (
    SELECT tt.visitid, tt.visitcount
    FROM (SELECT t1.visitid, 1 + COUNT(*) OVER (PARTITION BY t1.doctorinspection) AS visitcount
          FROM akuz.t_doctor_inspection_re t1
          WHERE t1.doctorinspection = tdi.visitid
         ) tt
    INNER JOIN akuz.t_visit t2 ON tt.visitid = t2.visitid
    ORDER BY t2.visitdate DESC
    LIMIT 1
    ) lv ON TRUE
WHERE di.visitid = tdi.visitid;