SQL case 0 然后 NULL
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32251298/
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
SQL case 0 then NULL
提问by xyron
I wanna get NULL when the number in my table is 0. Can I achieve this using SQL?
当我的表中的数字为 0 时,我想获得 NULL。我可以使用 SQL 来实现吗?
SELECT ID,
Firstname,
Lastname,
CASE Number
WHEN 0 THEN NULL
END
FROM tPerson
Error:
错误:
At least one of the result expressions in a CASE specification must be an expression other than the NULL constant.
CASE 规范中的至少一个结果表达式必须是 NULL 常量以外的表达式。
Thanks in advance!
提前致谢!
回答by Thorsten Kettner
As others have mentioned you forgot to tell your CASE statement to return the number in case the number is not null.
正如其他人提到的,您忘记告诉您的 CASE 语句返回数字,以防数字不为空。
However in SQL Server you can use NULLIF, which I consider more readable:
但是在 SQL Server 中,您可以使用 NULLIF,我认为它更具可读性:
select
id,
firstname,
lastname,
nullif(number, 0) as number
from tperson;
If you want to stick to standard SQL then stay with CASE:
如果您想坚持使用标准 SQL,请继续使用 CASE:
case when number = 0 then null else number end as number
回答by Bogdan Bogdanov
May be you need ELSE
:
可能你需要ELSE
:
SELECT
ID, Firstname, Lastname CASE Number WHEN 0 THEN NULL ELSE Number END
FROM tPerson
回答by koushik veldanda
SELECT ID, Firstname, Lastname,
CASE WHEN Number!=0 THEN Number END
FROM tPerson
回答by Shoe
In MySQL you can also use if
:
在 MySQL 中,您还可以使用if
:
select if(number = 0, null, number) ...
回答by Bulat
Try:
尝试:
SELECT ID, Firstname,
Lastname,
CASE Number WHEN 0 THEN NULL ELSE Number END
FROM tPerson