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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 11:47:32  来源:igfitidea点击:

Compare values of two columns then select the larger value

sqlsql-server-2008

提问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

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

在 T-SQL 中,IF命令用于程序控制。例如:

  • IF x THEN doSQLStatement1 ELSE doSQLStatement2
  • IF x THEN doSQLStatement1 ELSE doSQLStatement2



Within a SQL statement, you need CASE.

在 SQL 语句中,您需要CASE

CASE WHEN a > b THEN a ELSE b END

回答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.

这里有关于 SQL Fiddle 的完整示例

回答by Isaac Lopes

You can use CASE, but if one of the values is 'null', the 'null' is considered the greatest value.

您可以使用CASE,但如果其中一个值为 'null',则 'null' 被认为是最大值。

To solve this problem you can use GREATEST

要解决此问题,您可以使用GREATEST

SELECT GREATEST(column3, column4)
FROM Table1

回答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.