我想在 SQL 中将 (a,b) 和 (b,a) 归为一组 (a,b)
例如下面的集合
SELECT 'a' AS Col1, 'b' AS Col2
UNION ALL
SELECT 'b', 'a'
UNION ALL
SELECT 'c', 'd'
UNION ALL
SELECT 'a', 'c'
UNION ALL
SELECT 'a', 'd'
UNION ALL
SELECT 'b', 'c'
UNION ALL
SELECT 'd', 'a'
应该屈服
Col1 | Col2
a b
c d
a c
a d
b c
最佳答案
按按字母顺序选择对的 case 语句分组:
select case when col1 < col2 then col1 else col2 end as col1,
case when col1 < col2 then col2 else col1 end as col2
from (
select 'a' as col1, 'b' as col2
union all
select 'b', 'a'
union all
select 'c', 'd'
union all
select 'a', 'c'
union all
select 'a', 'd'
union all
select 'b', 'c'
union all
select 'd', 'a'
) t group by case when col1 < col2 then col1 else col2 end,
case when col1 < col2 then col2 else col1 end
http://sqlfiddle.com/#!3/9eecb7db59d16c80417c72d1/6977
如果您只是想要唯一值(而不是聚合分组),那么您可以使用 distinct
而不是 group by
select distinct case when col1 < col2 then col1 else col2 end as col1,
case when col1 < col2 then col2 else col1 end as col2
from (
select 'a' as col1, 'b' as col2
union all
select 'b', 'a'
union all
select 'c', 'd'
union all
select 'a', 'c'
union all
select 'a', 'd'
union all
select 'b', 'c'
union all
select 'd', 'a'
) t
关于sql - sql中对的分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37084523/