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:)
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
select distinct
case when a<b then a else b end
,case when a<b then b else a end
from @t
;
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
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With