简体   繁体   中英

Select distinct values based on multiple column from table

I am having below dummy table

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

which will give output as below

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

I wants to find the distinct values from that table like below

col1 col2
A    B
A    C
A    D

first row can be AB or BA same as second can be AC or CA

Is it possible?? We got the solution for above problem which is below

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

but if there is more than 2 column, then i wouldn't work

Let us assume the below scenario

Input

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

Output

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

then what would be the possible solution ?

Here is one method:

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

The following will work for Oracle and Postgres:

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

Online example: http://rextester.com/BZXC69735

    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
select col1, col2 from t where col1 <= col2
union
select col2, col1 from t where col1 > col2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM