Напишите запрос для отображения департамента и нет сотрудника, у которого в отделе есть максимум сотрудников. - PullRequest
0 голосов
/ 11 октября 2018

Напишите запрос, чтобы отобразить имя департамента и номер сотрудника, у которого нет максимального сотрудника .?

Здесь я опробовал следующий запрос:

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 OCL?

Ответы [ 3 ]

0 голосов
/ 11 октября 2018

В качестве альтернативы вы можете использовать аналитическую функцию 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

0 голосов
/ 11 октября 2018

Хотя то, что вы пытаетесь достичь, может быть сделано другими 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;
0 голосов
/ 11 октября 2018

Вы можете использовать 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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...