Test data and sample below.
Basically, we make a self-connection with the criteria of OR
, therefore either a = a or b = b OR a = b and b = a.
WHERE
in the subquery gives the maximum exception for each pair.
I think this should work for three repetitions as well (note I added the 6th line).
DECLARE @t table(id int, a int, b int) INSERT INTO @t VALUES (1,1,2), (2,2,1), (3,3,4), (4,0,5), (5,5,0), (6,5,0) SELECT * FROM @t WHERE id NOT IN ( SELECT a.id FROM @ta INNER JOIN @tb ON (aa=ba AND ab=bb) OR (ab=ba AND aa = bb) WHERE a.id > b.id)
source share