Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Distinct by comparing multiple columns SQL

Tags:

sql

I have a select query

Select col1,col2,col3 
from table;

The table contains following rows

col1 col2 col3 
A    | B  | C
B    | A  | C
C    | B  | C

I need to get the distinct result which contains a single combination A,B,C by comparing multiple columns.

Result Should be some thing like

col1 col2 col3 
A    | B  | C

the order can be changed of result rows.

How can I achieve this ?

like image 382
Praveen Avatar asked Nov 01 '22 13:11

Praveen


1 Answers

Please try out this, I am not sure about you proper requirement. But on sample data given above. I have came across this solution,

With CTE as
(
     Select MIN(col1) as col1 from MyTable
)
Select * from CTE
cross apply
    (
        Select MIN(col2) as col2 from MyTable
        where col2 <> CTE.col1
    )as a
cross apply
    (
        Select MIN(col3) as col3 from MyTable
        where col3 not in (CTE.col1,a.col2)
    )as b

DEMO HERE

like image 129
AK47 Avatar answered Nov 09 '22 05:11

AK47