MySQL新手:查询查找每个员工的姓名,其薪水超过其所在部门所有员工的平均工资

时间:2013-03-29 02:06:41

标签: mysql average

打印薪水超过所有员工平均工资的每位员工的姓名 他或她的部门。

  • emp (eid: integer, ename: string, age: integer, salary: real)
  • works (eid: integer, did: integer, pct_time: integer)
  • dept (did: integer, dname: string, budget: real, managerid: integer)

这就是我所拥有的:

SELECT ename FROM emp
WHERE salary > all (
  SELECT AVG(salary) FROM dept, works
  WHERE emp.eid = works.eid AND works.did = dept.did)

问题在于,我似乎得到的薪水大于每个工人平均薪水的人的名字。我想我不需要指向department表的链接,但是当我尝试编辑上面的字符串时,我仍然得到相同的结果。

2 个答案:

答案 0 :(得分:1)

使用子查询获得平均值的方法是合理的,但您需要按部门对子查询进行分组。然后,您可以通过以下方式加入子查询:

  • 部门ID相等(等值),
  • 员工工资高于平均部门工资(非等值)

这是查询...

SELECT emp.ename, dept.dname, emp.salary, DeptAvg.AvgSal
FROM emp
INNER JOIN works ON emp.eid = works.eid
INNER JOIN dept ON works.did = dept.did
INNER JOIN (
    SELECT works.did, AVG(emp.salary) AS AvgSal
    FROM emp
    INNER JOIN works ON emp.eid = works.eid
    GROUP BY works.did) DeptAvg
  ON DeptAvg.did = works.did AND emp.salary > DeptAvg.AvgSal

此查询显示员工姓名,部门名称,员工薪资和平均部门薪水。我做到了,所以你可以看到数字并测试它。您可以删除任何列,查询仍应有效。

答案 1 :(得分:0)

SELECT emp.ename,dept.dname,emp.salary,avg(emp.salary) as DeptAvgSalary
FROM emp 
INNER JOIN works ON emp.eid = works.eid
INNER JOIN dept ON works.did = dept.did
group by dept.did 
having emp.salary>DeptAvgSalary