如何在oracle中选择下面的case case语句

时间:2014-10-23 10:12:54

标签: sql oracle

我想做以下事情。

如果COLUMN_A<> COLUMN_B然后将COLUMN_A,COLUMN_B和另一个虚拟列状态打印为不正常。我尝试了以下内容。

SELECT CASE WHEN COLUMN_A <> COLUMN_B 
THEN SELECT COLUMN_A, COLUMN_B,status as 'NOT OK'--(im not sure what to do here)
 END
FROM TABLE_1

嗨,对不起,我无法正确表达问题。

这是我所期待的。

ROW   COLUMN_A      COLUMN_B    STATUS
1     100                        OK
2     250           350          NOT OK
3     300           NULL         NULL COLUMN_A
4     NULL          400          NULL COLUMN_B

Based on the below condition .

If COLUMN_A = COLUMN_B (THEN DISPLAY ROW1 Output)
COLUMN_A != COLUMN_B (THEN DISPLAY ROW2 oUTPUT)
IF COLUMN_B IS NULL THEN DISPLAY ROW3 Output 
IF COLUMN_A IS NULL THEN DISPLAY ROW4 Output

2 个答案:

答案 0 :(得分:1)

尝试选择列并使用案例评估每一行:

SELECT COLUMN_A, COLUMN_B
, CASE WHEN COLUMN_A <> COLUMN_B THEN 'Not OK' ELSE 'OK' END AS [Status]
FROM Table1

根据您的意见,您可以在单个案例陈述中包含多个案例: *更新 - 虽然不优雅,但您可以使用自己的声明处理每个必要的案例。由于您要确定哪个列为null,因此您需要先评估该列,然后执行not equals比较。

SELECT COLUMN_A, COLUMN_B, COLUMN_C, COLUMN_D
, CASE WHEN COLUMN_A IS NULL THEN 'A is NULL'
WHEN COLUMN_B IS NULL THEN 'B is NULL'
WHEN COLUMN_C IS NULL THEN 'C is NULL'
WHEN COLUMN_C IS NULL THEN 'D is NULL'
WHEN COLUMN_A <> COLUMN_B THEN 'Not OK' 
WHEN COLUMN_A <> COLUMN_B THEN 'Not OK AB' 
WHEN COLUMN_B <> COLUMN_C THEN 'Not OK BC' 
WHEN COLUMN_C <> COLUMN_D THEN 'Not OK CD'

ELSE 'OK' END AS [Status]
FROM Table1

但是,如果你只想要三个列,一个联合或联合都是合理的方式。

答案 1 :(得分:0)

如果要为NULL值获取不同的输出,则必须明确处理它们:

with table1(column_a, column_b) as (
  select 1, 2 from dual union all
  select 2, 2 from dual union all
  select 3, null from dual union all
  select null, 4 from dual union all
  select null, null from dual
)
SELECT 
  COLUMN_A, 
  COLUMN_B,
  CASE 
    WHEN COLUMN_A <> COLUMN_B THEN 'Not OK' 
    WHEN column_a is null and column_b is null then 'both NULL'
    WHEN column_a is null then 'A null'
    WHEN column_b is null then 'B null'
ELSE 'OK' END AS Status
FROM Table1