没有任何分组依据时,count返回<< air >>

时间:2019-07-01 20:02:55

标签: oracle group-by count coalesce

这是我的SQL:

select 
  count(*)
from
  sysdba.dw_cmap_arf_tmp
left join SYSDBA.TABLE1 rrc 
  on rrc.part_work_order = pwo
left join sysdba.TABLE2 R
  on rrc.run_number = R.RUN_NUMBER
where 
  upper(run_type) like '%FEE%'
group by 
  pwo;

没有任何分组依据时,计数将返回--air--。它为null也不为空白。我已经修改了上面的SQL,如下所示。

select 
  '>>' || count(*) || '<<' as blah
from
  sysdba.dw_cmap_arf_tmp
left join SYSDBA.TABLE1 rrc 
  on rrc.part_work_order = pwo
left join sysdba.TABLE2 R
  on rrc.run_number = R.RUN_NUMBER
where 
  upper(run_type) like '%ANNEAL%'
group by 
  pwo;

但是,当我在上面编写语句以执行更新时,我得到了null。因此尝试合并,但得到了相同的结果。

有人知道我可以用null或0替换--air--吗?谢谢!

P.S。我做了一些研究,但找不到任何东西……如果已经有类似的问题了,请提前道歉。

谢谢!

1 个答案:

答案 0 :(得分:1)

这是您当前拥有的(基于Scott的EMP表):由于没有部门50,因此您没有选择(您是 air 我想是在谈论)。

SQL> with your_current_query as
  2    (select count(*) cnt
  3     from emp
  4     where deptno = &deptno
  5     group by job
  6    )
  7  select cnt
  8  from your_current_query;
Enter value for deptno: 50

no rows selected

只是为了表明如果那里有数据,它实际上会返回一些东西:

SQL> /
Enter value for deptno: 30

       CNT
----------
         4
         1
         1

SQL>

好;现在,要在没有选择行的情况下执行某事,请结合使用从DUAL表中选择的“虚拟”行的联合:

SQL> with your_current_query as
  2    (select count(*) cnt
  3     from emp
  4     where deptno = &deptno
  5     group by job
  6    )
  7  select cnt
  8  from your_current_query
  9  -- add this: if YOUR_CURRENT_QUERY doesn't return anything, union it with
 10  -- a select from dual
 11  union all
 12  select 0
 13  from dual
 14  where 0 = (select count(*) from your_current_query);
Enter value for deptno: 50

       CNT
----------
         0

SQL>

所以:即使部门50中没有员工,结果还是为0。

再次显示行中出现的情况:

SQL> /
Enter value for deptno: 30

       CNT
----------
         4
         1
         1

SQL>

最后,您的查询-重写-如下所示:

with your_current_query as
  (select 
    count(*) cnt
   from
     sysdba.dw_cmap_arf_tmp
   left join SYSDBA.TABLE1 rrc 
     on rrc.part_work_order = pwo
   left join sysdba.TABLE2 R
     on rrc.run_number = R.RUN_NUMBER
   where 
     upper(run_type) like '%FEE%'
   group by 
     pwo
  )
select cnt from your_current_query
union all
select 0 
from dual
where 0 = (select count(*) from your_Current_query);

看看是否有帮助。