简体   繁体   English

使用嵌套的案例表达

[英]Using Nested Case Expression

I am stuck in properly using Nested Case Expression. 我被困在正确使用嵌套案例表达。

在此处输入图片说明

The requirement is to create the calculated column that will be either 0 or 1. If the name is 'abc' and ind = 1, then the value of calc column will be 1 . 要求是创建将为0或1的计算列。如果名称为'abc'且ind = 1,则calc列的值为1。 But if the name is 'abc' and salary is > 2000 . 但是,如果名称是'abc'并且薪水是> 2000。 then the value will be 1 again irrespective the value of ind. 则无论ind的值如何,该值都将再次为1。

I have written the below query using OR condition in CASE Expression but want to use the Nested CASE. 我已经在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

Below is the result: 结果如下:

在此处输入图片说明

You don't need nested CASE : 您不需要嵌套的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

I don't know why you need nested case expression, i would do instead of nested case expression that would be more efficient : 我不知道为什么你需要嵌套的case表达式,我会代替嵌套的case表达式来提高效率:

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

If you HAVE to have nested case expression then this is how you would write it: 如果您必须具有嵌套的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;

如果您使用的是SQL Server 2012及更高版本,则还可以使用如下所示的IIF语句:

select iif(name = 'abc' AND (salary > 2000 OR ind = 1), 1,0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM