5

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 ?

1
  • 3
    which RDBMS it is Oracle/mysql/SqlServe ? Commented Dec 12, 2014 at 10:21

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

0
SELECT * FROM table WHERE (col1 = 'A' AND col2 = 'B' AND col3 = 'C') 

4 Comments

OP wants to remove duplicate rows according to all three columns but the order should not matter. You are filtering by static values but apart from the fact that it was just an example it also incorrect because col3 = 'A' AND col1 = 'B' AND col2 = 'C' would also be allowed.
Yes, The values of the columns are not static !
Can you please add some explanation to your answer?
This would bring back the single combination A,B,C as requested in the question?
0

You can also go with this below query if the number of column and the values are known.

The CASE statement is the closest to IF in SQL SELECT CASE WHEN (col1 = 'A' and col2 = 'B' and col3='C') or (col1 = 'C' and col2 = 'A' and col3='B') or (col1 = 'B' and col2 = 'C' and col3='A' ) THEN 1 ELSE 0 END as RESULT, * FROM table 

From the result you can take the required output by checking the value of RESULT==1(integer)

If you want the result as a boolean value then do the CAST like ,

SELECT CAST( CASE WHEN (col1 = 'A' and col2 = 'B' and col3='C') or (col1 = 'C' and col2 = 'A' and col3='B') or (col1 = 'B' and col2 = 'C' and col3='A' ) THEN 1 ELSE 0 END as RESULT_INT) as RESUTL, * FROM table 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.