Differs in comparing multiple SQL columns

I have a select request

Select col1,col2,col3 from table; 

The table contains the following rows.

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

I need to get a great result that contains one combination of A, B, C, comparing multiple columns.

The result should be something like

 col1 col2 col3 A | B | C 

the order can be changed in the result lines.

How can i achieve this?

+5
source share
3 answers

Please try this, I'm not sure if you meet the requirements. But according to the example given above. I found 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

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

You can also refer to this query below if you know the number of columns and values.

 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 RESULT==1(integer)

If you want result as a boolean value , then do 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 
0
source

Source: https://habr.com/ru/post/1208874/


All Articles