我正在尝试解决一个简单的问题,但我正在抓住细节。
我有2张桌子,一张有员工,另一张有部门。我的问题:我正在尝试检查哪个部门拥有最多员工,并仅输出该特定部门。
到目前为止,我有:
select count(*) Number_of_employees
from department d, employee e
where d.department_id = e.department_id
group by department_name
输出:
NUMBER_OF_EMPLOYEES
----------------------
2
4
3
3
3
我的目标是只输出员工最多的部门,即4名员工的部门。
我尝试使用MAX和JOIN,但我对加入并不是很好,所以任何建议都将不胜感激。
答案 0 :(得分:3)
@Zsolt Botykai
我认为这是正确的,除了需要DESC的顺序,我认为你不能在查询中引用number_of_employees。 (无论如何你不能在oracle中)。
select department_name
from
(select department_name
,number_of_employees
from
( select department_name, count(*) Number_of_employees
from department d, employee e
where d.department_id = e.department_id
group by department_name)
order by Number_of_employees DESC)
where rownum = 1
答案 1 :(得分:3)
你可以这样做以避免rownum:
select
max(d.department_name) keep (dense_rank first order by count(1) desc) as department_name
, count(1) as number_of_employees
from employee e
inner join department d on (e.department_id = d.department_id)
group by d.department_name
;
答案 2 :(得分:1)
select department_name from
( select department_name, count(*) Number_of_employees
from department d, employee e
where d.department_id = e.department_id
group by department_name
order by 2 desc )
where rownum = 1
应该这样做。
HTH