首页 > 解决方案 > 如何在 oracle 选择查询中返回 0 以防空结果?

问题描述

我有一个查询,其中有数字数据类型列。如果结果集为空,则 O/P 为空白。我想0在那种情况下。

我的查询是

select nvl(infodata,0) 
from table1 
where group_id = 111 
  and appid in (select max(id) 
                from table1, table2 
                where status = 'A');

现在我的内部查询在这种情况下返回 null 。NVL似乎不适用于 infodata 列。请帮忙

标签: oracleoracle11g

解决方案


这种查询的结果是没有选择行

例如(基于 Scott 的EMPDEPT表,因为我没有你的,而且你没有发布测试用例),这个查询什么也不返回:

SQL> select e.deptno
  2  from emp e
  3  where e.ename = 'Littlefoot';

no rows selected

如果将其用作子查询,则结果等于您当前拥有的结果:

SQL> select nvl(d.dname, 'x') result
  2  from dept d
  3  where d.deptno in (select e.deptno
  4                     from emp e
  5                     where e.ename = 'Littlefoot'
  6                    );

no rows selected

但是,如果你应用聚合(见第 1 行),那么你会得到你想要的:

SQL> select nvl(max(d.dname), 'x') result
  2  from dept d
  3  where d.deptno in (select e.deptno
  4                     from emp e
  5                     where e.ename = 'Littlefoot'
  6                    );

RESULT
--------------
x

正如我所说:它适用于我的测试用例;可能,也可能不在你的身上。如果您发布示例数据,我们将有一些工作要做。


推荐阅读