如何统计每个部门的员工

时间:2014-08-03 07:22:03

标签: sql oracle

希望你们能够提供一些见解哦如何修改我的查询。

所需结果:仅显示员工人数超过2人的员工。 -----------这意味着我的结果应该只提供7行(部门销售和IT部门的3和4)

非常感谢任何帮助。

我有这个查询:

SELECT b.employee_id,b.salary, a.department_id, a.department_name,
  max(b.salary) over (partition by a.department_id) as max_sal
FROM        department a, employee b
WHERE       a.department_id(+) = b.department_id

这些是我目前的结果:

EMPLOYEE_ID     SALARY DEPARTMENT_ID DEPARTMENT_NAME         MAX_SAL
----------- ---------- ------------- -------------------- ----------
       7566       3000            10 ACCOUNTING                 3000 
       7999       2500            20 RESEARCH                   3000 
       7610       3000            20 RESEARCH                   3000 
       7921       2500            30 SALES                      3000 
       7952       2000            30 SALES                      3000 
       7900       3000            30 SALES                      3000 
       7934       1000            40 IT                         2900 
       7876       2000            40 IT                         2900 
       7788       2500            40 IT                         2900 
       7910       2900            40 IT                         2900 
       7603       4000            50 EXECUTIVE                  5000 
       7596       4500            50 EXECUTIVE                  5000 
       8000       2500                                          2500

13 rows selected

2 个答案:

答案 0 :(得分:3)

您可以使用count(*) over ()来确定每个部门的员工数量。由于您无法在where子句中使用窗口函数,因此需要子查询。

select  *
from    (
        select  e.employee_id
        ,       e.salary
        ,       e.department_id
        ,       d.department_name
        ,       max(salary) over (partition by e.department_id) as max_sal
        ,       count(*) over (partition by e.department_id) as dep_empl_count
        from    employee e
        join    department d
        on      e.department_id = d.id
        ) SubQueryAlias
where   dep_empl_count > 2

请使用join而非日期col1(+) = col2语法。

答案 1 :(得分:2)

SELECT b.employee_id,b.salary, a.department_id, a.department_name,
  max(b.salary) over (partition by a.department_id) as max_sal
FROM        department a, employee b
WHERE       a.department_id(+) = b.department_id
AND         a.department_id IN (
    SELECT department_id from employee
    GROUP BY department_id
    HAVING COUNT(employee_id) > 2
)