0

打印工资超过其部门所有员工平均工资的每位员工的姓名。

  • 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)

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

4

2 回答 2

1

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

  • 部门 ID 相等(equijoin),并且
  • 员工工资大于部门平均工资(非等值)

这是查询...

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

该查询显示员工姓名、部门名称、员工工资和部门平均工资。我这样做是为了让您可以查看数字并进行测试。您可以删除任何列,查询应该仍然有效。

于 2013-03-29T02:39:24.633 回答
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
于 2015-04-03T15:50:30.270 回答