我是Oracle的初学者,我想知道为什么我不能使用count函数进行求和。这是我查询和尝试的示例:
select job_id, SUM(count(job_id)) as "jobs"
from employees
group by job_id
错误:
ORA-00937:不是单组分组功能
我也尝试使用cte,但令我惊讶的是我不能:
with cte1 as (
select job_id, count(job_id) as "jobs"
from employees
group by job_id
)
select sum(jobs) from cte1
ORA-00904:“作业”:无效的标识符
答案 0 :(得分:3)
您可以嵌套聚合。但是您需要从选择列表中删除要分组的列:
select sum(count(*)) as "jobs"
from hr.employees
group by job_id;
jobs
107
这将计算每个作业的行数。然后总结这些。
与以下相同:
with jobs as (
select count(*) c
from hr.employees
group by job_id
)
select sum ( c ) from jobs;
SUM(C)
107
您的CTE失败,因为您引用了“工作”。这使其成为小写标识符,您需要在引号中引用该标识符以进行访问:
with cte1 as(
select job_id,
count( job_id ) as "jobs"
from hr.employees
group by job_id
)
select sum( "jobs" )
from cte1;
SUM("JOBS")
107
答案 1 :(得分:1)
您不需要多余的总和,您已经具有每个job_id的行数:
select job_id, count(job_id) as "jobs" from employees group by job_id