嵌套的case语句sql

时间:2015-07-03 23:00:40

标签: mysql sql sql-server

我在SQL中编写case语句时遇到问题。我的第一个问题是:是否可以在select语句中的SQL查询中将if语句编写为case语句?

如果不是,那么请查看下面的案例陈述,并帮助/指导我进入有效的格式。谢谢,非常感谢!

IF (var1 = 1){
do this1;
IF (var 1 = 2){
    Do this2;
    }Else{ 
    do something else1;
    }
Else if (Var 1 = 3){
    Do this3; 
    }Else{ 
    Do something else2;
    }   

这是我的个案陈述。我知道它不起作用,因为它不是一个有效的案例陈述。有人可以帮我做一个有效的案例陈述。提前谢谢。

    SELECT
CASE
    WHEN apple.type = 1 OR apple.type = 2
    THEN basket.S1
    ELSE 
        CASE 
            WHEN apple.type = 0 AND basket.S2 is null
            THEN basket.S1
            ELSE basket.S2  
        ELSE 
            CASE
                WHEN apple.type = 3 and basket.s3 is null
                THEN basket.S1
                ELSE basket.S3
            END
        END
    END 
FROM .....
WHERE ..... 

2 个答案:

答案 0 :(得分:3)

我认为你的案例陈述过于复杂,看你的第一个例子你的案例陈述应该相当简单,

像......那样......

SELECT CASE 
           WHEN @Var1 = 1 THEN 'Something 1'
           WHEN @Var1 = 2 THEN 'Something 2'
           WHEN @Var1 = 3 THEN 'Something 3'
           ELSE 'Something Else'
       END 
FROM .....
WHERE .....

你的案例陈述我们可以写这样的东西......

SELECT
    CASE
        WHEN apple.[type] IN (1,2)
        THEN basket.S1
        WHEN apple.type = 0 AND basket.S2 is null
        THEN basket.S1
        WHEN apple.type = 3 and basket.s3 is null
        THEN basket.S1
        ELSE basket.S3
    END

答案 1 :(得分:2)

由于您正在检查空值并替换非空值,因此可以使用COALESCE function缩短查询。

SELECT
  CASE
    WHEN apple.type IN (1, 2) THEN basket.s1
    WHEN apple.type = 0 THEN COALESCE(basket.s2, basket.s1)
    WHEN apple.type = 3 THEN COALESCE(basket.s3, basket.s1)
  END
FROM ...