案例陈述不适用于条件

时间:2019-11-06 08:16:35

标签: mysql

请帮助我提供此代码。

 SELECT (CASE LEFT(BRANCH_CODE, 1)
        WHEN '1' THEN 'NL'
        WHEN '2' THEN 'MM'
        WHEN '3' THEN 'SL'
        WHEN '4' THEN 'VIS'
        WHEN '5' THEN 'MIN'
        WHEN ('7' OR '8') THEN 'SA'
         END)  `REGION`,

这是结果:

Region
null
MM

结果应该是这样的:

Region
SA
MM

2 个答案:

答案 0 :(得分:0)

以下语法无效:

WHEN ('7' OR '8') THEN 'SA'

使用这种WHEN样式的ELSECASE之后的内容只能是文字值,而不是逻辑表达式。因此,您可以重构为:

SELECT
    CASE LEFT(BRANCH_CODE, 1)
        WHEN '1' THEN 'NL'
        WHEN '2' THEN 'MM'
        WHEN '3' THEN 'SL'
        WHEN '4' THEN 'VIS'
        WHEN '5' THEN 'MIN'
        WHEN '7' THEN 'SA'                -- repeat the 'SA' predicate twice
        WHEN '8' THEN 'SA' END AS REGION
FROM yourTable;

如果您想将78的情况合并到一个WHEN中,则必须使用更长的CASE形式:

SELECT
    CASE WHEN LEFT(BRANCH_CODE, 1) = '1' THEN 'NL'
         WHEN LEFT(BRANCH_CODE, 1) = '2' THEN 'MM'
         WHEN LEFT(BRANCH_CODE, 1) = '3' THEN 'SL'
         WHEN LEFT(BRANCH_CODE, 1) = '4' THEN 'VIS'
         WHEN LEFT(BRANCH_CODE, 1) = '5' THEN 'MIN'
         WHEN LEFT(BRANCH_CODE, 1) = '7' OR
              LEFT(BRANCH_CODE, 1) = '8' THEN 'SA' END AS REGION
FROM yourTable;

第二个版本非常丑陋,恕我直言,我可能会坚持使用第一个版本,它只是在两个地方重复了SA谓词。

答案 1 :(得分:0)

尝试在“ CASE”语句中应用多个条件语句时,我遇到了类似的问题。

我通过在“ WHEN”语句之后移动测试来解决它:

SELECT (CASE 
    WHEN LEFT(BRANCH_CODE, 1) = '1' THEN 'NL'
    WHEN LEFT(BRANCH_CODE, 1) = '2' THEN 'MM'
    WHEN LEFT(BRANCH_CODE, 1) = '3' THEN 'SL'
    WHEN LEFT(BRANCH_CODE, 1) = '4' THEN 'VIS'
    WHEN LEFT(BRANCH_CODE, 1) = '5' THEN 'MIN'
    WHEN LEFT(BRANCH_CODE, 1)  IN ('7' OR '8') THEN 'SA'
 END)  `REGION`,