0

我正在使用 oracle 的 SQL Developer。首先,我有这张表:

Name           Null     Type         
-------------- -------- ------------ 
EMPLOYEE_ID    NOT NULL NUMBER(6)    
FIRST_NAME              VARCHAR2(20) 
LAST_NAME      NOT NULL VARCHAR2(25)  
DEPARTMENT_ID           NUMBER(4)    

我想检索(选择)员工最多的部门的 ID。我通过一个语句来检索每个部门的所有员工人数:

select count(employee_id), department_id
from employees
group by department_id;

它给了我类似的东西:

count(employee_id)   |     department_id
---------------------|------------------
      6                       100
     16                        30
      1                        12

我想做的只是检索department_id30 个,它(在这种情况下)拥有最多的员工。

4

1 回答 1

1

在 Oracle 中执行此操作的典型方法:

select department_id
from (select count(employee_id), department_id
      from employees
      group by department_id
      order by count(employee_id) desc
     ) t
where rownum = 1;

如果您有潜在的重复并想要所有部门 ID,那么加入 max 或分析函数是一种更好的方法。例如:

select department_id
from (select count(employee_id), department_id,
             rank() over (order by count(employee_id) desc) as seqnum
      from employees
      group by department_id
     ) t
where seqnum = 1;
于 2013-05-28T20:02:21.563 回答