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 ex
Just so we don't return null:
SELECT IIF( a > b, a, COALESCE( a, b )) -- coalesce or isnull
FROM wherever
Here's a query to test it:
with whatever as (
select null as a, 1 as b
UNION
select 1 as a, null as b
union
select 1 as a, 0 as b
union
select 0 as a, 1 as b
union
select null as a, null as b
)
select( iif( a > b, a, isnull( b, a )))
from whatever
Should return
null
1
1
1
1
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.
select column1, coloumn2, case when column3 < column4 then column4 else coloum3 end from table.
I would start by creating a view.
CREATE VIEW t_c
SELECT id, c1 AS c FROM t
UNION
SELECT id, c2 AS c FROM t;
Then I would select from that view.
SELECT id, MAX(c) FROM t_c GROUP BY id;
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
You can use CASE, but if one of the values is 'null', the 'null' is considered the greatest value.
To solve this problem you can use GREATEST
SELECT GREATEST(column3, column4)
FROM Table1