select count(*), department_id
from employees
group by department_id
having count(*) > avg(count(*));
我只想选择>平均编号。
答案 0 :(得分:1)
您可以在having
子句中使用子查询:
select count(*), department_id
from employees
group by department_id
having count(*) > (select avg(cnt)
from (select count(*) as cnt
from employees
group by department_id
)
);
不需要额外级别的子查询。也可以写成:
select count(*), department_id
from employees
group by department_id
having count(*) > (select count(*) / nullif(count(distinct department_id), 0)
from employees
);
这只是通过将员工总数除以部门数来计算部门中的平均员工数。
答案 1 :(得分:1)
您需要将平均值计算为:
select avg(counter) from (select count(*) as counter from employees group by department_id)
进行比较:
select
count(*),
department_id
from employees
group by department_id
having
count(*) > (select avg(counter) from (select count(*) as counter from employees group by department_id));
答案 2 :(得分:0)
您也可以将cross join
用作
select e2.department_id
from employees e2
cross join (select count(e.empno) / count(distinct e.department_id) avg_emp
from employees e) e1
group by e2.department_id, avg_emp
having count(*) > e1.avg_emp;