在case语句TSQL中嵌套的If-Statement

时间:2017-12-20 13:26:58

标签: sql sql-server tsql

在TSQL中,我必须为某些值创建许多列,基于布尔值。

C1 | C2 | EdittedCol |
-----------------------
0  | 1  | not allowed
1  | 1  | allowed
1  | 0  | not allowed
and so on...

我目前正在搞乱,多个嵌套案例,使用IF语句更好的方法吗?

SELECT C1, C2, 
       CASE when C1 = 1 and C2 = 1 then 'allowed' else 
          CASE when C1 = 0 then 'not allowed - C1 = 0' else
          CASE when C2 = 0 then 'not allowed - C2 = 0' 
       end end end as EdittedCol
FROM myTestTable

返回:

C1 | C2 | EdittedCol |
-----------------------
0  | 1  | not allowed - C1 = 0
1  | 1  | allowed
1  | 0  | not allowed - C2 = 0
and so on...

2 个答案:

答案 0 :(得分:1)

您可以使用PIVOTUNPIVOT进行此操作。

DECLARE @EdittedCol TABLE (C1 INT,  C2 INT) 
INSERT INTO @EdittedCol VALUES
(0,1),
(1,1),
(1,0),
(0,0) -- I also added 0-0 scenario 


;WITH UNPVT AS 
(
    SELECT *, CASE WHEN VALUE = 0 THEN COL + ' = ' + CAST(VALUE AS varchar) ELSE '' END NotAllowedCol 
    FROM 
        ( SELECT ROW_NUMBER() OVER(ORDER BY (SELECT 1)) RN, C1, C2 FROM @EdittedCol ) AS SRC 
            UNPIVOT( VALUE FOR COL IN ([C1],[C2])) UNPVT
)
SELECT C1, C2, 
    CASE WHEN C1 * C2 = 1 
    THEN 'allowed' 
    ELSE 'not allowed - ' +  STUFF(EdittedCol,1,1,'') END EdittedCol 
FROM (SELECT RN, VALUE, COL FROM UNPVT) SRC
PIVOT( MAX(VALUE) FOR COL IN ([C1],[C2])) PVT
CROSS APPLY (SELECT ',' + NotAllowedCol FROM UNPVT WHERE UNPVT.RN = PVT.RN AND VALUE = 0 FOR XML PATH('')) X(EdittedCol)

结果:

C1          C2          EdittedCol
----------- ----------- -----------------------------------------
0           1           not allowed - C1 = 0
1           1           allowed
1           0           not allowed - C2 = 0
0           0           not allowed - C1 = 0,C2 = 0

答案 1 :(得分:0)

如果我明白你在做什么,你需要使用&按位运算符

SELECT C1, C2, C3, 
    case C1 & C2 & C3 when 1 then 'Allowed' ELSE 'Not Allowed' END AS EdittedCol 
FROM myTestTable;