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

标签 tsql case

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

相关文章:

sql-server - 查询返回两行

tsql - T-SQL 中临时表索引的最佳使用

sql-server - 更新和左外连接语句

sql - SELECT SQL 变量 - 我应该避免使用这种语法并始终使用 SET 吗?

sql - 从 SQL Server 表中选择具有最大日期的不同行?

c# - 性能 : should I make one or multiple queries to database

sql - 在子句中包含许多值 - SQL

sql - ORACLE-CASE 需要 INTO?

c - 带有大小写开关和枚举的工作日

SQL CASE 表达式 - 设置局部变量的值