oracle ELSE case 无论如何都会运行

oracle ELSE case runs regardless

我有一个案例陈述(myCol 是一个数字):

select case when myCol < 0 then 0 else round(POWER(10,AVG(LOG(10,myCol))),2) end myCol from myTable where id = 123 group by myCol;

但 Oracle 似乎 运行 else 子句不管,当 myCol 为负数 (-2.75) 时,POWER 或 LOG 函数抛出 ORA-01428: argument '-2.75' is out of range。如果 myCol < 0,我认为 else 子句将被忽略,但也许 Oracle 正在 运行ning?

之前编译整个语句

我也试过使用 decode(sign(myCol)... 但还是失败了。

我该如何处理?

我会说你发布的查询不完整。为什么?正因如此:

SQL> with test (mycol) as
  2    (select  2    from dual union all
  3     select -2.75 from dual
  4    )
  5  select case when myCol < 0 then 0
  6              else round(POWER(10,AVG(LOG(10,myCol))),2)
  7         end myCol
  8  from test;
select case when myCol < 0 then 0
                 *
ERROR at line 5:
ORA-00937: not a single-group group function


SQL>

但是,当您添加 group by 子句时,会出现您提到的错误:

SQL> with test (mycol) as
  2    (select  2    from dual union all
  3     select -2.75 from dual
  4    )
  5  select case when myCol < 0 then 0
  6              else round(POWER(10,AVG(LOG(10,myCol))),2)
  7         end myCol
  8  from test
  9  group by mycol;
            else round(POWER(10,AVG(LOG(10,myCol))),2)
                                           *
ERROR at line 6:
ORA-01428: argument '-2.75' is out of range


SQL>

怎么办?一种选择是应用 abs 函数,因为它是 GROUP BY 导致你的问题 - 它将整个结果数据集分成行,每个 mycol 单独,这就是 -2.75 变为 超出范围

SQL> with test (mycol) as
  2    (select  2    from dual union all
  3     select -2.75 from dual
  4    )
  5  select mycol original_value,
  6         case when myCol < 0 then 0
  7              else round(POWER(10,AVG(LOG(10,abs(myCol)))),2)
  8         end myCol                           ---
  9  from test                               -- this
 10  group by mycol;

ORIGINAL_VALUE      MYCOL
-------------- ----------
         -2,75          0
             2          2

SQL>