Incoorect计数结果

时间:2016-11-25 17:03:59

标签: oracle analytic-functions

我有两个数据表Employees和Departments。我想展示每个部门的员工人数,每个部门的工资平均等等。我的代码是:

select d.department_id, d.department_name, count(e.last_name) Employees,
avg(e.salary) Avg_Salary, e.last_name, e.salary, e.job_id
from departments d, employees e
where d.department_id = e.department_id
group by d.department_id, d.department_name, e.last_name, e.salary, e.job_id
order by d.department_id;

这段代码运行正常,但员工人数和平均工资的结果并不是我想要的。我的结果是:

Department_ID Department_Name Employees Avg_Salary Last_Name Salary Job_ID
------------- --------------- --------- ---------- --------- ------ ------
10            Administration  1         4400       Whalen    4400   AD_ASST
20            Marketing       1         6000       Fay       6000   MK_REP
20            Marketing       1         13000      Hartstein 13000  MK_MAN

如您所见,员工数量显示每位员工1,而不是每个部门的总数;并且Avg_Salary与薪水相同,而不是每个部门的实际薪资平均值。

这是我想要的结果:

 Department_ID Department_Name Employees Avg_Salary Last_Name Salary Job_ID
-------------  --------------- --------- ---------- --------  ------ ------
10             Administration  1         4400       Whalen    4400   AD_ASST
20             Marketing       2         9500       Fay       6000   MK_REP
20             Marketing       2         9500       Smith     13000  MK_MAN

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

应该这样做 - 使用分析函数:

select d.department_id, d.department_name,
       count(e.last_name) over (partition by d.department_id) Employees,
       avg(e.salary) over (partition by d.department_id) Avg_Salary,
       e.last_name, e.salary, e.job_id
from departments d, employees e
where d.department_id = e.department_id
order by d.department_id;