Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare values of two columns then select the larger value

Tags:

I need to query a table and select 3 of the values of 4 columns. I need to compare the values of the 3rd column and the fourth column and select the larger value.

For example:

column1  column2  column3  column4  hello    hello      3        5     hi       hi         7        1    

I need to return:

column1  column2  Hybrid  hello    hello     5     hi       hi        7    

I have been trying to use IF/ELSE but I just can't seem to get the syntax correct

like image 681
broguyman Avatar asked Oct 24 '12 20:10

broguyman


People also ask

Can you use conditional formatting to compare two columns?

Conditional Formatting Navigate to the "Home" option and select duplicate values in the toolbar. Next, navigate to Conditional Formatting in Excel Option. A new window will appear on the screen with options to select "Duplicate" and "Unique" values. You can compare the two columns with matching values or unique values.


2 Answers

In T-SQL the IF command is for programatic control. For example:

  • IF x THEN doSQLStatement1 ELSE doSQLStatement2


Within a SQL statement, you need CASE.

CASE WHEN a > b THEN a ELSE b END 
like image 98
MatBailie Avatar answered Nov 06 '22 10:11

MatBailie


Try this code:

SELECT column1, column2,        (CASE WHEN column3 > column4 THEN column3 ELSE column4 END)   FROM Table1 

Result:

COLUMN1   COLUMN2  Hybrid  hello     hello      5   hi         hi       7 

Here you have complete sample on SQL Fiddle.

like image 20
Yaroslav Avatar answered Nov 06 '22 10:11

Yaroslav