oracle分组和联盟

时间:2015-06-08 14:46:45

标签: sql oracle group-by

我想结合2个查询,但在oracle中遇到错误。

select count(*) as faultCount,
       COMP_IDENTIFIER 
from CORDYS_NCB_LOG 
where AUDIT_CONTEXT='FAULT' 
union 
select count(*) as responseCount,
       COMP_IDENTIFIER 
from CORDYS_NCB_LOG 
where AUDIT_CONTEXT='RESPONSE' 
group by COMP_IDENTIFIER  
order by responseCount; 

两个查询完全单独运行。但是当使用union时,它表示ORA-00904:" RESPONSECOUNT":无效标识符

3 个答案:

答案 0 :(得分:5)

您遇到的错误

在Oracle中,最好始终以相同的方式命名每个UNION子查询中的每一列。在您的情况下,以下应该有效:

select count(*) as theCount,
       COMP_IDENTIFIER 
from CORDYS_NCB_LOG 
where AUDIT_CONTEXT='FAULT' 
group by COMP_IDENTIFIER -- don't forget this
union 
select count(*) as theCount,
       COMP_IDENTIFIER 
from CORDYS_NCB_LOG 
where AUDIT_CONTEXT='RESPONSE' 
group by COMP_IDENTIFIER  
order by theCount; 

另见:

Curious issue with Oracle UNION and ORDER BY

一个好的解决方法当然是使用a_horse_with_no_name建议的索引列引用

您真正想要的查询

但是,从您的评论中,我怀疑您想要编写完全不同的查询,即:

select count(case AUDIT_CONTEXT when 'FAULT'    then 1 end) as faultCount,
       count(case AUDIT_CONTEXT when 'RESPONSE' then 1 end) as responseCount,
       COMP_IDENTIFIER 
from CORDYS_NCB_LOG 
where AUDIT_CONTEXT in ('FAULT', 'RESPONSE')
group by COMP_IDENTIFIER  
order by responseCount; 

答案 1 :(得分:2)

联合的列名由第一个查询确定。因此,您的第一列实际上名为FAULTCOUNT

但是对联合结果进行排序的最简单方法是使用列索引:

select ...
union 
select ...
order by 1;

您很可能还想使用UNION ALL,这样可以避免在两个查询之间删除重复项,并且比普通UNION

更快

答案 2 :(得分:0)

在Union或Union中,所有查询列名都由第一个查询列名确定。

在您的查询中,将“order by responseCount”替换为“order by faultCount。