Oracle:按请求计数和分组不返回0而不是0

时间:2014-07-04 12:58:20

标签: sql oracle

对于给定的acc_ene

,我的查询计算满足条件ene.ene_type = 'PRCECO'deal.deal_scope = 'Y'的{​​{1}}的数量

以下是查询:

run_id

但是,如果不存在此类select run.run_id, 35, count(*), sysdate from dt_runs run join acc_deals deal on deal.deal_cnt_id = run.deal_cnt_id join acc_ene ene on ene.deal_id = deal.deal_id and ene.ene_cnt_id = run.ene_cnt_id where ene.ene_type = 'PRCECO' and deal.deal_scope = 'Y' and run.run_id = '&1' group by run.run_id, 35, sysdate; ,则查询不返回acc_ene,而是返回0。 有没有办法修改我的查询以使其返回0

我已尝试使用nvl(count(*), 0)( - >不是更好)和此查询,这似乎有效:

select run.run_id, 34, (select count(*) from acc_ene ene where ene.ene_type = 'PRCECO'), sysdate
from dt_runs run, acc_deals deal, acc_ene ene 
where ene.deal_id = deal.deal_id
and ene.ene_cnt_id = run.ene_cnt_id
and deal.deal_scope = 'Y'
and run.run_id = '&1'
and deal.deal_cnt_id = run.deal_cnt_id 
group by run.run_id, 34, sysdate;

但后来我尝试了另一个ene.ene_type = 'IMM',我知道表中有记录。它返回了acc_ene类型'IMM'的总数,而不是特定运行的此类acc_ene的数量。

我做错了什么?

1 个答案:

答案 0 :(得分:3)

当没有数据时,你得到了一个GROUP BY没有结果,这就是SQL的工作方式。

尝试使用外部联接来改变它:

select run.run_id, 35, count(ene.deal_id), sysdate
from dt_runs run
left join acc_deals deal 
  on deal.deal_cnt_id = run.deal_cnt_id
 and deal.deal_scope = 'Y'
left join acc_ene ene
  on ene.deal_id = deal.deal_id 
 and ene.ene_cnt_id = run.ene_cnt_id
 and ene.ene_type = 'PRCECO'
where run.run_id = '&1'
group by run.run_id, 35, sys date;

或者摆脱GROUP BY,你只需要一个run_id的数据:

select min(run.run_id), 35, count(*), sysdate
from dt_runs run
join acc_deals deal on deal.deal_cnt_id = run.deal_cnt_id
join acc_ene ene on ene.deal_id = deal.deal_id and ene.ene_cnt_id = run.ene_cnt_id
where ene.ene_type = 'PRCECO'
and deal.deal_scope = 'Y'
and run.run_id = '&1';

我无法测试Oracle是否接受没有group by的常量,否则你可能必须使用

select min(run.run_id), min(35), count(*), min(sys date)