TSQL CASE 语法结束 = nn

TSQL CASE SYNTAX END = nn

我遇到了从 COGNOS 生成的以下代码:

  CASE 
    WHEN CASE 
            WHEN 'FIELD1' LIKE 'VAL1'
                THEN 1
            WHEN 'FIELD1' LIKE 'VAL2'
                THEN 2
            WHEN 'FIELD1' LIKE 'VAL3'
                THEN 3
            ELSE 4
            END = 1
        THEN 'M'
    WHEN CASE 
            WHEN 'FIELD1' LIKE 'VAL1'
                THEN 1
            WHEN 'FIELD1' LIKE 'VAL2'
                THEN 2
            WHEN 'FIELD1' LIKE 'VAL3'
                THEN 3
            ELSE 4
            END = 2
        THEN 'Q'
    WHEN CASE 
            WHEN 'FIELD1' LIKE 'VAL1'
                THEN 1
            WHEN 'FIELD1' LIKE 'VAL2'
                THEN 2
            WHEN 'FIELD1' LIKE 'VAL3'
                THEN 3
            ELSE 4
            END = 3
        THEN 'Y'
    ELSE 'T'
    END AS 'VAL4'

我无法确定 'END = nn' 后面的“=”运算符的意义。此外,CASE 块似乎是重复的,不提供区分值。

这可能更清楚

 CASE 
   WHEN (
     CASE 
        WHEN 'FIELD1' LIKE 'VAL1' THEN 1
        WHEN 'FIELD1' LIKE 'VAL2' THEN 2
        WHEN 'FIELD1' LIKE 'VAL3' THEN 3
        ELSE 4
     END
   ) = 1 THEN 'M'

   WHEN (
     CASE 
       WHEN 'FIELD1' LIKE 'VAL1' THEN 1
       WHEN 'FIELD1' LIKE 'VAL2' THEN 2
       WHEN 'FIELD1' LIKE 'VAL3' THEN 3
       ELSE 4
     END 
   ) = 2 THEN 'Q'

   WHEN (
     CASE 
       WHEN 'FIELD1' LIKE 'VAL1' THEN 1
       WHEN 'FIELD1' LIKE 'VAL2' THEN 2
       WHEN 'FIELD1' LIKE 'VAL3' THEN 3
       ELSE 4
     END
   ) = 3 THEN 'Y'
   ELSE 'T'
 END AS 'VAL4'

本质上,对于每个 'when' 选项,外部案例都有另一个 case case 语句

所以,

  • 如果 Field1 是 'VAL1' 那么结果将是 'M'
  • 如果 Field1 是 'VAL2' 那么结果将是 'Q'
  • 如果 Field1 是 'VAL3' 那么结果将是 'Y'

如果 Field1 是其他任何东西,它将是 'T'

比@SpaceUser7448 进一步简化,看起来像:

SELECT 
CASE 
    WHEN 'FIELD1' LIKE 'VAL1' THEN 'M'
    WHEN 'FIELD1' LIKE 'VAL2' THEN 'Q'
    WHEN 'FIELD1' LIKE 'VAL3' THEN 'Y'
    ELSE 'T'
END AS 'VAL4'