根据表中的多列选择不同的值

时间:2017-02-20 11:33:57

标签: sql

我在虚拟表下面

select * from (
select 'A' as col1, 'B' as col2 from dual 
union
select 'B' as col1, 'A' as col2 from dual 
union
select 'A' as col1, 'C' as col2 from dual 
union
select 'C' as col1, 'A' as col2 from dual 
union
select 'A' as col1, 'D' as col2 from dual 
)a

将输出如下

col1 col2
A   B
A   C
A   D
B   A
C   A

我想从该表中找到不同的值,如下所示

col1 col2
A    B
A    C
A    D

第一行可以是A B或B A与第二行相同可以是A C或C A

有可能吗? 我们得到了以下问题的解决方案

select distinct least(col1, col2), greatest(col1, col2)
from the_table;

但是如果有超过2列,那么我就不会工作

让我们假设以下情景

输入

 col1 col2 col3
    A   B   E
    A   C   E
    A   D   E
    B   A   F
    C   A   E

输出

 col1 col2 col3
    A   B   E
    A   D   E
    B   A   F
    C   A   E

然后可能的解决方案是什么?

4 个答案:

答案 0 :(得分:2)

这是一种方法:

select col1, col2
from t
where col1 <= col2
union all
select col1, col2
from t
where col1 > col2 and
      not exists (select 1 from t t2 where t2.col1 = t.col2 and t2.col2 = t.col1);

答案 1 :(得分:2)

以下内容适用于Oracle和Postgres:

select distinct least(col1, col2), greatest(col1, col2)
from the_table;

在线示例:http://rextester.com/BZXC69735

答案 2 :(得分:0)

    select DISTINCT * from (
select 'A' as col1, 'B' as col2 from dual 
union
select 'B' as col1, 'A' as col2 from dual 
union
select 'A' as col1, 'C' as col2 from dual 
union
select 'C' as col1, 'A' as col2 from dual 
union
select 'A' as col1, 'D' as col2 from dual 
)a

答案 3 :(得分:0)

select col1, col2 from t where col1 <= col2
union
select col2, col1 from t where col1 > col2