如何获得列之间的唯一组合?

时间:2018-12-27 23:22:13

标签: sql sql-server tsql sql-server-2014

具有如下表格:

F    G
---- ----
123  ABC
ABC  123
DEF  123

我需要获取:

F    G
---- ----
123  ABC
DEF  123

3 个答案:

答案 0 :(得分:3)

这是您想要的吗?

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

答案 1 :(得分:0)

假设您有一列,可让您对行进行唯一排序,例如int id或date列,则以下内容应适用:

[Authorize]

答案 2 :(得分:0)

此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