找到最大下属数的经理姓名

时间:2017-01-05 16:29:23

标签: sql oracle

我需要编写SQL查询(对于Oracle),它显示具有最大下属数的经理名称。

表的结构:

EMPNO INT PRIMARY KEY
ENAME VARCHAR NOT NULL
MGR_ID INT

MGR_ID员工' attribute是经理的EMPNO(主键)。

到目前为止我已尝试过:

SELECT ENAME FROM EMP WHERE 
(SELECT COUNT(MGR_ID) FROM EMP GROUP BY MGR_ID)=
(SELECT MAX(SELECT COUNT(MGR_ID) FROM EMP GROUP BY MGR_ID) FROM EMP);

2 个答案:

答案 0 :(得分:1)

WITH mgr_cnt
     AS (  SELECT mgr_id, COUNT (*) cnt
             FROM EMP
         GROUP BY mgr_id)
SELECT e.ename
  FROM emp e,
       (SELECT mgr_id, cnt, DENSE_RANK () OVER (ORDER BY cnt DESC) rnk
          FROM mgr_cnt) t
 WHERE e.empno = t.mgr_id and t.rnk=1;

a_horse_with_no_name建议的另一个版本

SELECT e.ename FROM
   emp e
   INNER JOIN 
     ( 
      SELECT mgr_id, DENSE_RANK () OVER (ORDER BY COUNT (*) DESC) rnk
        FROM emp
    GROUP BY mgr_id
    )list
   ON ( list.mgr_id=e.empno)
  WHERE  list.rnk=1

PS:查询未测试

答案 1 :(得分:0)

解决办法是

with temp_tab as
(
select mgr_id, count(*) num_emp from emp group by mgr_id order by 2 desc
)
select * from temp_tab where rownum<=1;