最高部门平均工资

时间:2018-06-22 22:40:21

标签: mysql sql

我有员工和部门表,我需要找到部门的最高平均工资。我们可以有两个大于1的最大值。我尝试了以下查询

select dept.name,avg(employee.sal)
from employee,dept
where dept.id=empolyee.id
group by dept.name
LIMIT 1

但是我只能管理一个最高平均薪水,如何获得超过一个最大值的查询

1 个答案:

答案 0 :(得分:1)

您需要与另一个获得最大平均值的查询联接,然后返回具有相同平均值的所有行。

SELECT t1.name, t1.avgSal
FROM (SELECT d.name, avg(e.sal) AS avgSal
      FROM employee AS e
      JOIN dept AS d ON d.id = e.dept_id
      GROUP BY d.name) AS t1
JOIN (SELECT d.name, avg(e.sal) AS avgSal
      FROM employee AS e
      JOIN dept AS d ON d.id = e.dept_id
      GROUP BY d.name
      ORDER BY avgSal DESC
      LIMIT 1) AS t2
ON t1.avgSal = t2.avgSal