WITH ranked AS (
SELECT
*,
rn = ROW_NUMBER() OVER (PARTITION BY RecId ORDER BY Dt DESC)
FROM TableA
)
SELECT
r1.Id,
r1.Dt,
r1.Stat,
r1.RecId
FROM ranked r1
INNER JOIN ranked r2 ON r1.RecId = r2.RecId AND r2.rn = 1
WHERE r1.Stat = 2
UPPDATERA efter uppdateringen av frågan
WITH ranked AS (
SELECT
*,
rn = ROW_NUMBER() OVER (PARTITION BY RecId ORDER BY Dt DESC)
FROM TableA
)
SELECT
Id,
Dt,
Stat,
RecId
FROM ranked
WHERE Stat = 2 AND rn = 1