SQL 比较两列的值,然后选择较大的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13057408/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Compare values of two columns then select the larger value
提问by broguyman
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.
我需要查询一个表并选择 4 列值中的 3 个。我需要比较第三列和第四列的值并选择较大的值。
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
我一直在尝试使用 IF/ELSE 但我似乎无法获得正确的语法
回答by MatBailie
回答by Yaroslav
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 sampleon SQL Fiddle.
回答by Isaac Lopes
回答by user1427302
Just so we don't return null:
只是为了不返回 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
回答by Roger C S Wernersson
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;
回答by Florin Stingaciu
select column1, coloumn2, case when column3 < column4 then column4 else coloum3 end from table.