我有以下格式的2个表:
在每个部门工作的员工中,有多少员工的员工人数超过部门员工的平均员工人数。
我以下列格式查看结果:
Dept Name | Num of Emp
engineering | 10
science | 15
答案 0 :(得分:2)
SELECT deptName, cnt
FROM (
SELECT departmentID, COUNT(*) AS cnt
FROM employee
GROUP BY
departmentID
HAVING COUNT(*) >=
(
SELECT AVG(cnt)
FROM (
SELECT COUNT(*) AS cnt
FROM employee
GROUP BY
departmentID
)
)
) e
JOIN departments d
ON d.departmentID = e.departmentID
在Oracle
中,您可以使用更优雅的分析函数:
SELECT DeptName, cnt
FROM (
SELECT q.*, AVG(cnt) OVER() AS acnt
FROM (
SELECT departmentID, COUNT(*) AS cnt
FROM employee
GROUP BY
departmentID
) q
) e
JOIN departments d
ON d.departmentID = e.departmentID
WHERE cnt >= acnt
答案 1 :(得分:1)
由于员工只能在一个部门,因此员工的平均数量就是员工总数超过部门总数。那怎么样:
SELECT dept.name, COUNT(emp.id) AS employeeCount
FROM emp INNER JOIN dept ON emp.deptId = dept.id
GROUP BY dept.name
HAVING (COUNT(emp.id) >
(SELECT COUNT(*) FROM emp) /
(SELECT COUNT(*) FROM dept))