UPDATE #table1
SET Comflag = CASE WHEN
EXISTS (
SELECT 1
FROM (
SELECT MAX(CleanDate) AS MaxCleanDate
FROM #table a
INNER JOIN T#table1 b
ON a.CodeID = b.CodeID
AND a.Subcode = b.Subcode
AND a.TranID = b.TranID
WHERE a.Code = @CodeID
AND a.Subcode = @Subcode
) AS MaxCleanDateEvent
WHERE MaxCleanDate > DATEDIFF(hh, -24, GETDATE())
) THEN 1 ELSE 0 END