如何获得列之间的唯一组合?
How to get unique combinations between columns?
table喜欢:
F G
---- ----
123 ABC
ABC 123
DEF 123
我需要获得:
F G
---- ----
123 ABC
DEF 123
这是你想要的吗?
select min(f), max(g)
from t
group by (case when f < g then f else g end),
(case when f < g then g else f end);
此 CTE 匹配 f/g 和 g/f 匹配(仅保留一个匹配)和非匹配的并集:
Create Table #tbl
(
F VarChar(10),
G VarChar(10)
)
Insert Into #tbl Values
('123','ABC'),
('ABC','123'),
('DEF','123'),
('123','DEF'),
('123','XYZ')
With CTE As
(
Select x.F, x.G, Row_Number() Over (Order By (Select Null)) As rn
From #tbl x
inner Join #tbl y On x.F = y.G And x.G = y.F
) ,
CTE1 As
(
Select x.F, x.G
From #tbl x
left Join #tbl y On x.F = y.G And x.G = y.F
Where y.F Is Null
)
Select F,G From CTE Where rn % 2 <> 0
Union All
Select F,G From CTE1
结果:
F G
ABC 123
123 DEF
123 XYZ
table喜欢:
F G
---- ----
123 ABC
ABC 123
DEF 123
我需要获得:
F G
---- ----
123 ABC
DEF 123
这是你想要的吗?
select min(f), max(g)
from t
group by (case when f < g then f else g end),
(case when f < g then g else f end);
此 CTE 匹配 f/g 和 g/f 匹配(仅保留一个匹配)和非匹配的并集:
Create Table #tbl
(
F VarChar(10),
G VarChar(10)
)
Insert Into #tbl Values
('123','ABC'),
('ABC','123'),
('DEF','123'),
('123','DEF'),
('123','XYZ')
With CTE As
(
Select x.F, x.G, Row_Number() Over (Order By (Select Null)) As rn
From #tbl x
inner Join #tbl y On x.F = y.G And x.G = y.F
) ,
CTE1 As
(
Select x.F, x.G
From #tbl x
left Join #tbl y On x.F = y.G And x.G = y.F
Where y.F Is Null
)
Select F,G From CTE Where rn % 2 <> 0
Union All
Select F,G From CTE1
结果:
F G
ABC 123
123 DEF
123 XYZ