如何在Oracle SQL中找到员工最多的部门

时间:2016-01-05 01:06:29

标签: sql oracle ora-00937

我正在尝试在演示HR模式中找到拥有最多员工的部门:

SELECT d.DEPARTMENT_ID, d.DEPARTMENT_NAME, MAX(COUNT(e.EMPLOYEE_ID))
FROM departments d INNER JOIN employees e ON d.DEPARTMENT_ID = e.DEPARTMENT_ID
GROUP BY d.DEPARTMENT_ID, d.DEPARTMENT_NAME

该脚本不使用MAX()

6 个答案:

答案 0 :(得分:2)

您可以打包当前查询(减去MAX)并选择人头数最多的部门组。

WITH CTE (DEPARTMENT_ID, DEPARTMENT_NAME, empCount) AS
(
    SELECT d.DEPARTMENT_ID, d.DEPARTMENT_NAME, COUNT(e.EMPLOYEE_ID) AS empCount
    FROM departments d INNER JOIN employees e ON d.DEPARTMENT_ID = e.DEPARTMENT_ID
    GROUP BY d.DEPARTMENT_ID, d.DEPARTMENT_NAME
)
SELECT DEPARTMENT_ID, DEPARTMENT_NAME
FROM CTE
WHERE empCount = (SELECT MAX(t.empCount) FROM CTE t)

答案 1 :(得分:1)

您可以尝试使用desc on count(e.EMPLOYEE_ID)按顺序获取部门,并使用ROWNUM将结果限制为第一行,如下所示:

select * from (select d.DEPARTMENT_ID, d.DEPARTMENT_NAME, count(e.EMPLOYEE_ID) cnt 
from departments d inner join employees e on d.DEPARTMENT_ID = e.DEPARTMENT_ID 
group by d.DEPARTMENT_ID, d.DEPARTMENT_NAME order by 3 desc) where ROWNUM=1

坦率地说,我无法针对Oracle DB测试此查询,因为我的机器上只安装了Derby DB,而且它不支持ROWNUM伪插入列。

答案 2 :(得分:0)

使用像

这样的ORDER BY子句
select d.DEPARTMENT_ID, d.DEPARTMENT_NAME, 
count(e.EMPLOYEE_ID) as employe_count
from departments d
inner join employees e
on d.DEPARTMENT_ID = e.DEPARTMENT_ID
group by d.DEPARTMENT_ID, d.DEPARTMENT_NAME
order by count(e.EMPLOYEE_ID) desc
offset 0 rows fetch next 1 rows only;

注意:OFFSETFETCH NEXT仅在Oracle 12.1

开头提供

答案 3 :(得分:0)

您可以使用 COUNT()OVER()分析函数。

例如,使用employees架构中的标准HR表:

SQL> SELECT DISTINCT department_id,
  2    COUNT(department_id) OVER(PARTITION BY department_id) rn
  3  FROM hr.employees t
  4  ORDER BY rn DESC;

DEPARTMENT_ID         RN
------------- ----------
           50         45
           80         34
           30          6
          100          6
           60          5
           90          3
           20          2
          110          2
           10          1
           40          1
           70          1
                       0

12 rows selected.

SQL>

从上面的结果集中找到<{1>} 最高员工

department_id

答案 4 :(得分:0)

请查询查询:

SELECT *
FROM
(
SELECT d.DEPARTMENT_ID, d.DEPARTMENT_NAME ,COUNT(e.EMPLOYEE_ID) EMP_COUNT
FROM HR.departments d
INNER JOIN HR.employees e
ON d.DEPARTMENT_ID = e.DEPARTMENT_ID
GROUP BY d.DEPARTMENT_ID, d.DEPARTMENT_NAME
ORDER BY EMP_COUNT DESC
)
WHERE ROWNUM=1

答案 5 :(得分:0)

select dname,deptno,loc from dept where deptno=(select deptno from (select deptno,count(*) as emp_count from emp group by deptno order by emp_count desc) where rownum=1)