CASE ... ELSE *在Oracle SQL中忽略*

时间:2015-03-24 01:45:14

标签: sql oracle

我试图在SELECT语句中使用CASE,这将改变列中可能的12个值。

CASE WHEN grade = 0 THEN 'R2'
WHEN grade = -1 THEN 'R1'
ELSE --ignore--
END AS "Grade level"

有没有人知道如何替换--ignore--,以便只改变那两个可能的值?我真的不想为列中的每个值写出单独的WHEN。

5 个答案:

答案 0 :(得分:4)

由于成绩是一个数字,因此您需要将其转换为字符,以便它适合R1R2

CASE WHEN grade = 0 THEN 'R2'
WHEN grade = -1 THEN 'R1'
ELSE to_char(grade)
END AS "Grade level"

答案 1 :(得分:1)

也许你想要这个?

(CASE WHEN grade = 0 THEN 'R2'
      WHEN grade = -1 THEN 'R1'
      ELSE grade
 END) AS "Grade level"

我对此建议犹豫不决,因为grade似乎是一个数字数量,但case语句正在评估字符串。但是,它似乎接近你想要的。

编辑:

正如预期的那样,你需要转换一些东西。我建议:

(CASE WHEN grade = 0 THEN 'R2'
      WHEN grade = -1 THEN 'R1'
      ELSE cast(grade as varchar2(255))
 END) AS "Grade level"

但是,如果您想将grade设置为该值,那么您只会收到另一个转换错误,因为您无法将'R2'分配给某个数字。

答案 2 :(得分:1)

只需删除ELSE部分:

CASE WHEN grade = 0 THEN 'R2'
WHEN grade = -1 THEN 'R1'
END AS "Grade level"

答案 3 :(得分:1)

取决于您的完整查询也许您可以将忽略条件的反向逻辑带到where子句:

CASE WHEN grade = 0 THEN 'R2'
WHEN grade = -1 THEN 'R1'
ELSE -- 1 or any value you can put here it dose not come in result becase of where clause
END AS "Grade level"
.....
where grade in (0,-1)

编辑:如果您能够在where子句中使用,则可以使上述查询更简单(减少一个when):

...
CASE WHEN grade = 0 THEN 'R2'
     ELSE 'R1'
END AS "Grade level"
.....
where grade in (0,-1)

答案 4 :(得分:0)

您可以将整个内容作为子查询放入FROM子句中,然后引用在其下方的单独WHERE子句中命名的列...

SELECT * 
FROM
    (SELECT.....
    CASE WHEN grade = 0 THEN 'R2'
    WHEN grade = -1 THEN 'R1'
    ELSE NULL
    END AS "Grade level" 
    FROM .....
    WHERE.....)

WHERE "Grade level" is not null
;