如何使用mysql获得最大平均值?

时间:2015-12-01 04:24:11

标签: mysql

如何获取max average sal中的employee table;

我有

  工作,deptno和sal。

我用它来查询:

select max(avg(sal))
from emp
group by job;

但它不起作用。

2 个答案:

答案 0 :(得分:0)

我尝试将您的表创建为:

mysql> SELECT * FROM emp;
+------+--------+-------+
| job  | deptno | sal   |
+------+--------+-------+
| SSD  |      1 | 58000 |
| SD   |      1 | 20000 |
| GD   |      1 | 35000 |
| AO   |      2 | 40000 |
| AhO  |      2 | 25000 |
| AhO  |      2 | 55000 |
| SSD  |      1 | 68000 |
+------+--------+-------+
7 rows in set (0.00 sec)

我运行你的查询,所以我得到了:

mysql> select max(avg(sal)) from emp group by job;
ERROR 1111 (HY000): Invalid use of group function

那是因为你已经嵌套了两个聚合函数。

要解决您的问题,我已更改您的查询,如下所示:

SELECT 
    job, 
    AVG(sal) AS average_salary
FROM emp 
GROUP BY job
ORDER BY average_salary DESC
LIMIT 1;

+------+----------------+
| job  | average_salary |
+------+----------------+
| SSD  |     63000.0000 |
+------+----------------+

答案 1 :(得分:0)

不是将max()函数应用于avg()。尝试引入按工作分组的所有员工的avg()。

 SELECT Avg(sal) AS avg_sal
     FROM   emp
     GROUP  BY job;

然后将max()函数应用于子查询。

 SELECT Max(avg_sal)
    FROM   (SELECT Avg(sal) AS avg_sal
    FROM   emp
    GROUP  BY job) AS sub_tab;