sql unique records puzzle

时间:2016-10-20 19:31:29

标签: sql sql-server

The puzzle is to select unique pairs. Syntax in the following example is for Mssql

declare @t table (a int, b int)

insert into @t (a,b) values (1,2)
insert into @t (a,b) values (2,1)
insert into @t (a,b) values (1,3)
insert into @t (a,b) values (3,1)
insert into @t (a,b) values (5,6)


select * from @t -- it outputs 5 records.

I need to get unique pairs only regardless of the order a,b, which should give me three records

Output should be

(1,2),(1,3),(5,6)

I am out of ideas and will appreciate the help:)

3 个答案:

答案 0 :(得分:10)

one way (demo) would be

SELECT DISTINCT v.a,
                v.b
FROM   @t
       CROSS APPLY (VALUES(a,b),
                          (b,a)) v(a, b)
WHERE  v.a <= v.b 

答案 1 :(得分:3)

select      distinct 

            case when a<b then a else b end
           ,case when a<b then b else a end 

from        @t
;

答案 2 :(得分:3)

您没有请求它,但这将保留列的顺序,即始终返回现有行:

select a,b
from @t as t1
where not exists(
  select * from @t as t2
  where  t1.a = t2.b
    and t1.b = t2.a
    and t1.a > t2.a
);