gpt4 book ai didi

tsql : is it possible to do nested case statements in a select?

转载 作者:行者123 更新时间:2023-12-02 23:42:05 25 4
gpt4 key购买 nike

如何将嵌套的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com