SQL 我们可以在没有 else 语句的情况下编写 case 语句吗

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40101963/
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 04:56:59  来源:igfitidea点击:

Can we write case statement without having else statement

sqlsql-serversql-server-2008selectcase

提问by Red Devil

I have this query:

我有这个查询:

select case when id=1 then 'A'
when id=2 then 'B'
end 
from test

It is giving me o/p as

它给了我 o/p 作为

Id
A
B
NULL
NULL
NULL

Id
A
B
NULL
NULL
NULL

I don't want to have NULLvalues in my output, I only want to compare in A and B, is it possible in case statement.

我不想NULL在我的输出中有值,我只想在 A 和 B 中进行比较,是否可以在 case 语句中。

回答by Mureinik

A caseexpression can only manipulate the value of an expression, not remove rows from the result. If you want to omit the nulls from the result, you'll have to add a whereclause:

case表达式只能操纵表达式的值,而不是从结果中删除行。如果null要从结果中省略s,则必须添加一个where子句:

SELECT CASE WHEN id = 1 THEN 'A'
            WHEN id = 2 THEN 'B'
       END 
FROM   test
WHERE  id IN (1, 2) -- HERE

回答by Unnikrishnan R

You can use a WHEREclause to restrict the output.

您可以使用WHERE子句来限制输出。

SELECT CASE WHEN id=1 THEN 'A'
WHEN id=2 THEN 'B'
END 
FROM test
WHERE id IN (1,2)

Or if you wanted to showcase some other value instead of nulluse an elsepart inside the CASEstatement.

或者,如果您想展示一些其他值而不是在语句中null使用某个else部分CASE

SELECT CASE WHEN id=1 THEN 'A'
WHEN id=2 THEN 'B' ELSE 'Invalid'
END 
FROM test