我试图在演示 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()
.
您可以包装当前查询(减去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)
您可以尝试按 count(e.EMPLOYEE_ID) 上的 desc 顺序获取部门,并通过将结果限制在第一行来使用 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 伪列。
请找到查询:
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
使用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;
注意:OFFSET
并且FETCH NEXT
仅可从Oracle 12.1
您可以使用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>
要从上述结果集中找到department_id
最多员工:
SQL> SELECT department_id
2 FROM
3 (SELECT department_id,
4 row_number() OVER(ORDER BY rn DESC) rn
5 FROM
6 ( SELECT DISTINCT department_id,
7 COUNT(department_id) OVER(PARTITION BY department_id) rn
8 FROM hr.employees t
9 )
10 )
11 WHERE rn = 1;
DEPARTMENT_ID
-------------
50
SQL>
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)