oracle中的group by和union
group by and union in oracle
我想联合 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;
两个查询 运行 完美 individually.but 当使用 union 时,它说 ORA-00904: "RESPONSECOUNT": 无效标识符
联合的列名由第一个查询确定。所以你的第一列实际上被命名为 FAULTCOUNT
。
但对并集的结果进行排序的最简单方法是使用列索引:
select ...
union
select ...
order by 1;
您很可能还想使用 UNION ALL
,它可以避免删除两个查询之间的重复项,并且比普通的 UNION
更快
您 运行 遇到的错误
在 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
当然,一个好的解决方法是使用
建议的索引列引用
您真正想要的查询
但是,根据您的评论,我怀疑您想要编写一个完全不同的查询,即:
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;
在 Union 或 Union 中,所有查询列名均由第一个查询列名确定。
在您的查询中,将 "order by responseCount" 替换为“order by faultCount.
我想联合 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;
两个查询 运行 完美 individually.but 当使用 union 时,它说 ORA-00904: "RESPONSECOUNT": 无效标识符
联合的列名由第一个查询确定。所以你的第一列实际上被命名为 FAULTCOUNT
。
但对并集的结果进行排序的最简单方法是使用列索引:
select ...
union
select ...
order by 1;
您很可能还想使用 UNION ALL
,它可以避免删除两个查询之间的重复项,并且比普通的 UNION
您 运行 遇到的错误
在 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
当然,一个好的解决方法是使用
您真正想要的查询
但是,根据您的评论,我怀疑您想要编写一个完全不同的查询,即:
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;
在 Union 或 Union 中,所有查询列名均由第一个查询列名确定。
在您的查询中,将 "order by responseCount" 替换为“order by faultCount.