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
Can we write case statement without having else statement
提问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 NULL
values 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 case
expression can only manipulate the value of an expression, not remove rows from the result. If you want to omit the null
s from the result, you'll have to add a where
clause:
甲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 WHERE
clause 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 null
use an else
part inside the CASE
statement.
或者,如果您想展示一些其他值而不是在语句中null
使用某个else
部分CASE
。
SELECT CASE WHEN id=1 THEN 'A'
WHEN id=2 THEN 'B' ELSE 'Invalid'
END
FROM test