使用嵌套的案例表达

时间:2018-10-17 17:41:42

标签: sql sql-server tsql

我只能正确使用嵌套案例表达。

enter image description here

要求是创建将为0或1的计算列。 如果名称为“ abc”且ind = 1,则calc列的值为1。但是,如果名称是'abc'并且薪水是> 2000。那么无论ind的值如何,该值都将再次为1。

我已经在CASE表达式中使用OR条件编写了以下查询,但希望使用嵌套CASE。

select t.*,  case when (name = 'abc' and ind = 1 ) or (name = 'abc' and sal > 2000) 
                  then 1 
                  else 0 
                  end 
from test t

以下是结果:

enter image description here

4 个答案:

答案 0 :(得分:2)

您不需要嵌套的CASE

-- multiple conditions
select t.*, case when name = 'abc' and ind = 1 then 1
                 when name = 'abc' and sal > 2000 then 1 
                 else 0 end 
from test t

答案 1 :(得分:1)

我不知道您为什么需要嵌套case表达式,我会代替嵌套case表达式来提高效率:

select t.*, (case when name = 'abc' and (ind = 1 or sal > 2000) 
                  then 1 
                  else 0 
             end) 
from test t;

答案 2 :(得分:1)

如果您有嵌套的case表达式,那么这就是您的编写方式:

SELECT t.*, 
    CASE 
        WHEN name = 'abc' THEN
            CASE 
                WHEN ind = 1 THEN 1 
                WHEN sal > 2000 THEN 1 
                ELSE 0
            END 
        ELSE 0
    END
FROM test t;

答案 3 :(得分:0)

如果您使用的是flex-shrink及更高版本,还可以使用如下的SQL Server 2012语句:

IIF