我没有您的表,但 Scott 的示例架构包含类似的表 - dept(部门)和 emp(在这些部门工作的员工)。
每个部门有多少员工?
SQL> select deptno, count(*)
2 from emp
3 group by deptno
4 order by 2 desc;
DEPTNO COUNT(*)
---------- ----------
30 6 --> this is what you want, it has the most employees
20 5
10 3
是哪个部门的?
SQL> select * from dept order by deptno;
DEPTNO DNAME LOC
---------- -------------- -------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO --> it's SALES
40 OPERATIONS BOSTON
SQL>
这就是您尝试过的:并不是说它不起作用(Oracle 不允许您这样做),而是语法错误。 having 子句应该类似于 having count(*) = 25,而不仅仅是您的愿望成真(having max(count(*)) 读作“给我一个员工人数最多的部门”)。
SQL> select dname
2 from dept
3 where deptno in (select deptno from emp
4 group by deptno
5 having max(count(empno))
6 );
having max(count(empno))
*
ERROR at line 5:
ORA-00935: group function is nested too deeply
SQL>
那么,我们能做些什么呢?一个简单的选择是按员工人数对部门进行排名:
SQL> select deptno,
2 count(*) cnt,
3 rank() over (order by count(*) desc) rnk
4 from emp
5 group by deptno;
DEPTNO CNT RNK
---------- ---------- ----------
30 6 1 --> department 30 ranks as the highest
20 5 2
10 3 3
SQL>
剩下的很简单:将该查询用作 子查询(或 CTE,就像我一样),然后选择排名最高的查询:
SQL> with temp as
2 (select deptno,
3 count(*) cnt,
4 rank() over (order by count(*) desc) rnk
5 from emp
6 group by deptno
7 )
8 select d.dname
9 from dept d join temp t on t.deptno = d.deptno
10 where t.rnk = 1; --> the highest rank
DNAME
--------------
SALES
SQL>
销售。