Oracle中的案例功能 - 错误的回报

时间:2015-09-24 21:23:41

标签: sql oracle case

我有一个包含这些字段的表格: id, quarter, description, id_school.

这些表格包含以下数据:

ID | quarter | description 

12   A         1 YEAR         
12   S         1 Year         
12   A          DONE

我希望根据以下查询获得serie_school

select NVL(
    case 
        WHEN quarter  = 'S' AND 
             (UPPER(description ) LIKE 'DONE' OR 
              UPPER(description ) LIKE '%YEAR' OR  
              UPPER(description ) LIKE 'LANGUAGE') THEN -1 
        WHEN quarter  = 'A' AND 
            (UPPER(description ) LIKE 'DONE' OR  
             UPPER(description ) LIKE '%QUARTER' OR  
             UPPER(description ) LIKE '%STEP' OR 
             UPPER(description ) LIKE 'LANGUAGE') THEN -1 
        WHEN quarter  = 'T' THEN -1 
        ELSE -1 
    end, -1) nvl_return from test 

在我的查询中返回此内容是:

ID | quarter | description | nvl_return 

12   A         1 YEAR         1
12   S         1 Year         1 *- (this column has the wrong answer)*
12   A          DONE         -1

第2行的答案是错误的,因为QUARTER字段为'S'且说明字段为'year',因此它必须为-1,但在Oracle中正在返回1

有没有人可以帮我解决这个问题?

提前致谢

1 个答案:

答案 0 :(得分:1)

亚历山大,

检查您的陈述,我在其中添加了“< ======”以指出此列的各种可能金额。

select NVL(
    case 
        WHEN quarter  = 'S' AND 
             (UPPER(description ) LIKE 'DONE' OR 
              UPPER(description ) LIKE '%YEAR' OR  
              UPPER(description ) LIKE 'LANGUAGE') THEN -1<======= 
        WHEN quarter  = 'A' AND 
            (UPPER(description ) LIKE 'DONE' OR  
             UPPER(description ) LIKE '%QUARTER' OR  
             UPPER(description ) LIKE '%STEP' OR 
             UPPER(description ) LIKE 'LANGUAGE') THEN -1<====== 
        WHEN quarter  = 'T' THEN -1 <======
        ELSE -1 <=======
    end, -1 <-this will never happen) nvl_return from test 

在每种情况下都返回“-1”。 “-1”是您查询中返回的唯一列返回的唯一值。

所以当你说结果是:

ID | quarter | description | nvl_return 

12   A         1 YEAR         1
12   S         1 Year         1 *- (this column has the wrong answer)*
12   A          DONE         -1

很遗憾,您的查询无法生成您所说的结果。

尝试创建一个SQL小提琴,解释问题。 SQL Fiddle