计数结果不正确

Incoorect Count Results

我有两个数据表 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

如您所见,Employees count 显示每个员工 1,而不是每个部门的总数; Avg_Salary与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

我该如何解决这个问题?

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

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;