esh*_*haa 3 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;
Run Code Online (Sandbox Code Playgroud)
两个查询可以完美地独立运行。但是使用联合时,它会显示ORA-00904:“ RESPONSECOUNT”:无效的标识符
在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;
Run Code Online (Sandbox Code Playgroud)
也可以看看:
当然,一个好的解决方法是使用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;
Run Code Online (Sandbox Code Playgroud)