ALTER TABLE akuz.t_dispanserisation_init
    ADD CurrentMkb varchar(8) NULL
GO

ALTER TABLE akuz.t_dispanserisation_init
    ADD CurrentDiagnosis varchar(4096) NULL
GO

WITH cte AS (SELECT mov.DispanserisationInit, mov.Mkb, mov.Diagnosis
             FROM akuz.T_DISPANSERISATION_MOVENMENT mov
             WHERE NOT EXISTS (SELECT 1
                               FROM akuz.T_DISPANSERISATION_MOVENMENT mov2
                               WHERE mov2.DateEditing > mov.DateEditing
                                 AND mov.DispanserisationInit = mov2.DispanserisationInit))
UPDATE di
SET di.CurrentDiagnosis = COALESCE(cte.Diagnosis, di.Diagnosis),
    di.CurrentMkb       = COALESCE(cte.Mkb, di.Mkb)
FROM AKUZ.T_DISPANSERISATION_INIT di
LEFT JOIN cte ON di.MedicalRecordId = cte.DispanserisationInit
GO

