计数结果不正确
Posted
技术标签:
【中文标题】计数结果不正确【英文标题】:Incoorect Count Results 【发布时间】:2016-11-25 17:03:58 【问题描述】:我有两个数据表员工和部门。我想显示每个部门的员工人数,每个部门的平均工资等等。我的代码是:
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 与 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】:应该这样做 - 使用分析函数:
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;
【讨论】:
以上是关于计数结果不正确的主要内容,如果未能解决你的问题,请参考以下文章