如何在SQL查询的select子句中包含嵌套的if语句? 我知道使用case时条件然后X else y结束但是你如何以相同的方式为记录集中的每个记录做一个嵌套的。
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
这是正确的吗?
答案 0 :(得分:17)
是。案件中的案件没有任何问题。
虽然这是你的脚本,但是写得很好:
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
OR
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
OR
SELECT top 10
id,
coalesce(x.boy, x.girl, x.dog, x.cat) AS Who
from house x
答案 1 :(得分:16)
您可以使用COALESCE简化此操作。
SELECT TOP 10 id, COALESCE(x.boy, x.girl, x.dog, x.cat) as Who
FROM house x
答案 2 :(得分:0)
试试这个:
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
虽然您可以像Joe建议的那样使用coalesce
。