在SQL中找到最高的平均工资

时间:2017-09-29 09:37:47

标签: mysql sql

我有两张桌子,分别是教授和部门。我想做的是找到平均工资最高的部门。

两个表结构如下

教授

id name dept_id salary
1    x    3      20999
2     y   1      09000
3    z    2      10000
4   a     2      20000

部门

id dept_name
1  buk
2  rul
3  lok

示例输出

dept.name avg.salary
buk       10000
rul       15000
lok       20999

我已将这两个表合并,但无法使用这两个表找到平均值。

select department.name,professor.salary from professor , department where professor.id = department.id;

9 个答案:

答案 0 :(得分:1)

您应该使用AVG()并在avg栏中按desc应用订单并应用以下限制:

SELECT d.dept_name, AVG(p.salary)
FROM department d, professor p
WHERE p.dept_id = d.id
GROUP BY d.dept_name ORDER BY AVG(p.salary) DESC limit 0,1

我希望它会有所帮助。谢谢

答案 1 :(得分:1)

根据我对这个问题的理解,你似乎明确地希望部门名称具有最高教授平均薪水。这是聚合聚合情况,Max(AVG(薪水))作为过滤器。

<强>查询:

select dept_name,AVG(salary) as avg_salary from prof 
left join dept on prof.dept_id = dept.id group by dept_name having avg_salary 
IN(select Max(T1.avg_salary) from (select dept_id,AVG(salary) as avg_salary from prof group by dept_id ) as T1)

答案 2 :(得分:0)

尝试这样,你缺少聚合函数,在这种情况下AVG()GROUP BY

SELECT d.dept_name dept_name, AVG(p.salary) avg_salary
FROM department d, professor p
WHERE p.dept_id = d.id
GROUP BY d.dept_name

答案 3 :(得分:0)

学习使用正确的显式JOIN语法。简单的规则:从不FROM子句中使用逗号。

一种方法使用JOIN

select d.name, avg(p.salary) as avg_salary
from professor p join
     department d
     on p.dept_id = d.id
group by d.name
order by avg_salary desc
limit 1;

答案 4 :(得分:0)

这是我的2c ......

SELECT d.dept_name 
  FROM dept d 
  JOIN prof p 
    ON p.dept_id = d.id 
 GROUP 
    BY dept_name HAVING AVG(salary) = (SELECT AVG(salary) avg_salary 
                                         FROM prof 
                                        GROUP 
                                           BY dept_id 
                                        ORDER 
                                           BY avg_salary DESC 
                                        LIMIT 1);

答案 5 :(得分:0)

试试这个。

select d.dept_name as dname, avg(p.salary) as prof_salary from prof as p
inner join dept as d ON p.dept_id = d.id
group by dname order by prof_salary DESC limit 1;

答案 6 :(得分:0)

c:\>javac HelloWorld.java
c:\>appletviewer HelloWorld.html

答案 7 :(得分:0)

select b.name,round(avg(salary),4) from professor a
inner join department b on b.id= a.department_id
group by b.name,a.department_id having avg(a.salary) =
(
 select max(a.avgsal) from (select avg(salary) as avgsal from professor group by 
 department_id) a)

答案 8 :(得分:0)

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

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