Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql unique records puzzle

Tags:

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:)

like image 344
Michael EstrinOne Avatar asked Oct 20 '16 19:10

Michael EstrinOne


3 Answers

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 
like image 111
Martin Smith Avatar answered Oct 25 '22 00:10

Martin Smith


select      distinct 

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

from        @t
;
like image 36
David דודו Markovitz Avatar answered Oct 24 '22 23:10

David דודו Markovitz


You didn't request for it, but this will preserve the order of columns, i.e. always return an existing row:

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
);
like image 38
dnoeth Avatar answered Oct 24 '22 23:10

dnoeth