在sql中对对进行分组

时间:2016-05-07 04:33:12

标签: sql sql-server tsql

我想将(a,b)和(b,a)分组到SQL中的一个组(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

4 个答案:

答案 0 :(得分:4)

按案例陈述分组,按字母顺序选择对:

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

答案 1 :(得分:2)

作为替代方案,您可以使用UNION来实现此目的:

WITH cte AS (
    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')
SELECT col1, col2 FROM cte WHERE col1 < col2 OR col1 IS NULL
UNION
SELECT col2, col1 FROM cte WHERE col1 >= col2 OR col2 IS NULL
ORDER BY 1, 2

SQL fiddle

请注意,UNION会删除重复项。

如果您没有NULL个值,您当然可以省略OR条款中的WHERE部分。

答案 2 :(得分:0)

按值,(a,b)不等于(b,a)。如果要对它们进行相同处理,则需要为每一行创建新的键列。整体逻辑是

slideShowImages.get(position)

在您的情况下,WITH TableWithNewKey ( SELECT <original columns>, <new columns as key> FROM originaltable ) SELECT <new columns as key>, Aggregate(...) FROM TableWithNewKey GROUP BY <new columns as key> 是将(b,a)转换为(a,b)。交换a和b或其他函数可以是case语句。此表单适用于任意数量的列和其他相等比较。

答案 3 :(得分:0)

select col1, col2 from table 
except 
select col2, col2 from table where col2 > col1