如何将嵌套的 if 语句合并到 sql 查询的 select 子句中? 我知道在条件 then X else y 结束时使用 case,但是如何以相同的方式为记录集中的每条记录执行嵌套操作。
if x.boy is not null then
x.boy
else if x.girl is not null
then x.girl
else if x.dog is not null
then x.dog
else
x.cat
这是我的尝试:
SELECT top 10
id,
case when x.boy <> NULL then
x.boy
else case when x.girl <> NULL
x.girl
else case when x.dog <> NULL
x.dog
else x.cat
end as Who
from house x
这是正确的吗?
最佳答案
是的。案中案并没有什么问题。
尽管如此,这是您正确编写的脚本:
SELECT top 10
id,
case
when x.boy IS NOT NULL then x.boy
else case
when x.girl IS NOT NULL THEN x.girl
else case
when x.dog IS NOT NULL THEN x.dog
else x.cat
end
end
end as Who
from house x
或者
SELECT top 10
id,
case
when x.boy IS NOT NULL then x.boy
when x.girl IS NOT NULL THEN x.girl
when x.dog IS NOT NULL THEN x.dog
else x.cat
end as Who
from house x
或者
SELECT top 10
id,
coalesce(x.boy, x.girl, x.dog, x.cat) AS Who
from house x
关于tsql : is it possible to do nested case statements in a select?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3937232/