gpt4 book ai didi

sql - oracle中的group by和union

转载 作者:行者123 更新时间:2023-12-04 23:44:00 26 4
gpt4 key购买 nike

我想联合 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;

两个查询单独运行完美。但是当使用联合时,它说 ORA-00904: "RESPONSECOUNT": invalid identifier

最佳答案

你遇到的错误

在 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;

关于sql - oracle中的group by和union,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30712302/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com