编写查询以显示departno以及该departno拥有最大雇员的雇员人数。

时间:2018-10-11 02:36:16

标签: sql oracle

写一个查询以显示部门编号以及部门编号最大的员工人数。?

我在这里尝试了以下查询:

select deptno, count(*) as no_of_emp   
from emp 
group by deptno 
order by no_of_emp;  

但我越来越喜欢

Deptno   no_of_emp
30           6
20           4
10           4

但是我只需要第一行而不是全部。是否可以在oracle sql中仅显示第一条记录?

3 个答案:

答案 0 :(得分:1)

您可以使用ROWNUM

select * from
(
select deptno, count(*) as no_of_emp   
  from emp 
 group by deptno 
order by no_of_emp desc
) where rownum = 1; 

或者在12c及更高版本中,FETCH..FIRST

select deptno, count(*) as no_of_emp   
      from emp 
     group by deptno 
    order by no_of_emp desc fetch first 1 ROWS ONLY

答案 1 :(得分:0)

作为替代方案,您可以将max(count(*)) over (order by ...)分析函数与降序计数选项一起使用:

with emp( empno,ename,deptno ) as
(
  select 7839,'KING',10 from dual union all
  select 7698,'BLAKE',30 from dual union all
  select 7782,'CLARK',10 from dual union all
  select 7566,'JONES',20 from dual union all
  select 7788,'SCOTT',20 from dual union all
  select 7902,'FORD',20 from dual union all
  select 7369,'SMITH',20 from dual union all
  select 7499,'ALLEN',30 from dual union all
  select 7521,'WARD',30 from dual union all
  select 7654,'MARTIN',30 from dual union all
  select 7844,'TURNER',30 from dual union all
  select 7876,'ADAMS',20 from dual union all
  select 7900,'JAMES',30 from dual union all
  select 7934,'MILLER',10 from dual
)
select deptno, no_of_emp
from
(
select deptno, count(*) as no_of_emp, 
       max(count(*)) over (order by count(*) desc) as max_populated
  from emp
 group by deptno
 order by no_of_emp
 )
where max_populated = no_of_emp;

 DEPTNO NO_OF_EMP
 ------ ---------
   30       6

Rextester Demo

答案 2 :(得分:0)

尽管您要实现的目标可以通过其他sql查询更改您的查询来完成,如下所示:

SELECT * from (select deptno, count(*) as no_of_emp   
from emp 
group by deptno 
order by no_of_emp desc) where rownum<=1
;  

其他查询如下:

select deptno, count(*) as no_of_emp   
from emp 
group by deptno
having count(*)=(select max(count(*)) as no_of_emp   
from emp 
group by deptno)
order by no_of_emp desc;