我需要编写一个查询来列出所有员工以及他们拥有的下属数量

时间:2013-05-22 02:08:15

标签: sql oracle

不应该列出没有下属的员工,因为此查询也应该显示零下属。 我现在可以让所有员工都回到下属,但我似乎无法展示零下属的员工。

以下是目前的代码:

SELECT s.empno, s.ename, COUNT(*) as "Num_subordinates"
FROM emp e
JOIN emp s ON s.empno=e.super 
GROUP BY s.empno, s.ename;

3 个答案:

答案 0 :(得分:4)

您的陈述中唯一缺少的是使用LEFT JOIN而不是INNER JOIN。在ID计算时,您还需要指定*而不是LEFT JOIN,这样如果员工没有1,您就不会在COUNT()上产生SELECT e.empno, e.ename, COUNT(s.empno) as "Num_subordinates" FROM emp e LEFT JOIN emp s ON s.empno = e.super GROUP BY e.empno, e.ename 下级。

{{1}}

要进一步了解联接,请访问以下链接:

答案 1 :(得分:1)

<强>已更新

假设数据类似于以下

| EMPNO |     ENAME |  SUPER |
------------------------------
|     1 |  Manager1 | (null) |
|     2 | Employee1 |      1 |
|     3 | Employee2 |      1 |
|     4 | Employee3 |      1 |
|     5 |  Manager2 | (null) |
|     6 | Employee5 |      5 |
|     7 | Employee6 | (null) |

带有子查询的版本

SELECT e.empno, 
       e.ename, 
       (SELECT COUNT(*) 
          FROM emp 
         WHERE super = e.empno) "Num_subordinates"
  FROM emp e;

JOIN的版本。您必须使用LEFT JOIN,因为INNER JOIN会过滤掉必要的行,正如JW正确指出您需要COUNT s.empno而不是*

SELECT e.empno,
       e.ename,
       COUNT(s.empno) "Num_subordinates"
  FROM emp e LEFT JOIN emp s
    ON s.super = e.empno
 GROUP BY e.empno, e.ename
 ORDER BY e.empno

两个查询的输出

| EMPNO |     ENAME | NUM_SUBORDINATES |
----------------------------------------
|     1 |  Manager1 |                3 |
|     2 | Employee1 |                0 |
|     3 | Employee2 |                0 |
|     4 | Employee3 |                0 |
|     5 |  Manager2 |                1 |
|     6 | Employee5 |                0 |
|     7 | Employee6 |                0 |

SQLFiddle (对于两个查询)

答案 2 :(得分:0)

为您解决的一些问题:

1)分组自动加入:

SELECT s.empno, s.ename, COUNT(*) as "Num_subordinates"
FROM emp e RIGHT JOIN emp s ON s.empno=e.super 
GROUP BY s.empno, s.ename;

2)使用聚合从属计数离开联接:

SELECT s.*, c.num_subordinates as "Num_subordinates"
FROM emp s LEFT JOIN (SELECT super AS empno, COUNT(*) FROM emp GROUP BY super) AS c
  ON c.empno = s.empno;

或使用CTE:

WITH c AS (SELECT super AS empno, COUNT(*) FROM emp GROUP BY super)
SELECT s.*, c.num_subordinates as "Num_subordinates"
FROM emp s LEFT JOIN c
  ON c.empno = s.empno;

3)使用标量子查询:

SELECT s.*, (SELECT COUNT(*) FROM emp WHERE super=s.empno) AS "Num_subordinates"
FROM emp s;