此查询还应显示没有下属的员工应列为零下属。我目前可以返回所有下属的员工,但我似乎无法显示下属为零的员工。
这是到目前为止的代码:
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;
您的陈述中唯一缺少的是使用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
要进一步了解有关联接的更多信息,请访问以下链接:
更新
假设数据类似于以下
| 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
sinceINNER JOIN
过滤掉必要的行,正如 JW 正确指出的那样,您需要COUNT
ons.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(对于两个查询)
A few solutions for you problem:
1) grouped auto-join:
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) left join with aggregate subordinate counts:
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;
or using 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) using scalar sub-query:
SELECT s.*, (SELECT COUNT(*) FROM emp WHERE super=s.empno) AS "Num_subordinates"
FROM emp s;