请帮助我提供此代码。
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
答案 0 :(得分:0)
以下语法无效:
WHEN ('7' OR '8') THEN 'SA'
使用这种WHEN
样式的ELSE
或CASE
之后的内容只能是文字值,而不是逻辑表达式。因此,您可以重构为:
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;
如果您想将7
和8
的情况合并到一个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`,