sql - sql中对的分组

标签 sql sql-server tsql

我想在 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/

相关文章:

sql - 在 postgres 中拆分人名的最简单方法?

c# - LINQ SQL 查询,SubmitChanges 未将更改提交到数据库

sql - 当一个表有唯一的 FK 时,它是否应该有 PK?

SQL BETWEEN 逆序运算符条件值

sql - 如何在 SQL 语句语法中执行内联 if-then

sql - 在 SQL Server 存储过程中动态创建和选择表变量?

tsql - 匹配后如何使用MERGE获得标识值?

c# - 查找给定日期是否在日期范围列表中

sql - 搜索值列表的出现

sql - 如何在 SELECT INTO 之后保留数据类型?