SQL查询列表高于平均值的那些

时间:2009-09-25 14:30:23

标签: sql oracle plsql

我有以下格式的2个表:

  • employee(employeeID,EmployeeName,DepartmentID)
  • 部门(DepartmentID,DeptName)

在每个部门工作的员工中,有多少员工的员工人数超过部门员工的平均员工人数。

我以下列格式查看结果:

Dept Name   | Num of Emp
engineering | 10
science     | 15

2 个答案:

答案 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))