﻿UPDATE email SET 
   C_ALAPERTELMEZETT = 'T' 
  ,MODIFIER = 0
  ,LASTCHANGED = GETDATE()
FROM T_EMAIL_OSSZES email 
WHERE email.ID IN (
  SELECT MAX(e.ID)
  FROM T_EMAIL_OSSZES e
    INNER JOIN T_TANEV_OSSZES t ON t.Id = e.C_TANEVID AND t.C_AKTIV = 'T' AND t.TOROLT = 'F'
  WHERE 
    e.TOROLT = 'F' 
    AND e.C_GONDVISELOID IS NULL
    AND NOT EXISTS (SELECT ID FROM T_EMAIL_OSSZES e2 WHERE e2.C_FELHASZNALOID = e.C_FELHASZNALOID AND e2.C_TANEVID = e.C_TANEVID AND C_ALAPERTELMEZETT = 'T' AND e2.C_GONDVISELOID IS NULL AND e2.TOROLT = 'F')
  GROUP BY C_FELHASZNALOID
  )