gpt4 book ai didi

MySQL新手: Query to find the name of each employee whose salary exceeds the average salary of all employees in his or her department

转载 作者:行者123 更新时间:2023-11-29 13:57:03 27 4
gpt4 key购买 nike

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

  • emp(eid:整数,ename:字符串,年龄:整数,薪水:实数)
  • works(eid:整数,did:整数,pct_time:整数)
  • 部门(did:整数,dname:字符串,预算:实际,managerid:整数)

这就是我所拥有的:

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

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

最佳答案

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

  • 部门 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

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

关于MySQL新手: Query to find the name of each employee whose salary exceeds the average salary of all employees in his or her department,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15696281/

27 4 0