8

我正在用 SQL 编写这个查询:

select MAX(AVG(salary) ) from employees group by department_id;

首先我会得到分组department_id,但接下来会发生什么?

4

4 回答 4

16

If you have something like this

EmployeeId DepartmentId Salary
    1          1         10              
    2          1         30
    3          2         30
    4          2         40
    5          2         20
    6          3         40
    7          3         50

after grouping

DepartmentId    AVG(Salary) 
    1             (10+30)/2 = 20
    2             (30+40+20)/3 = 30
    3             (40+50)/2= 45

So the query below will return 45 as Maximum average salary for departmentId 3

SELECT MAX(x.avg) 
FROM ( SELECT AVG(salary)as avg FROM employees group by department_id)x;
于 2013-06-10T18:10:52.750 回答
5

Most likely, dependent on your RDBMS, this will need to bedone with a sub-query

select max(AveragesByDept.avgSalary) 
from ( 
    select avgSalary=avg(salary) 
    from employees
    group by department_id
    ) AveragesByDept
于 2013-06-10T18:04:49.500 回答
2

你可以通过只获得一排来做到这一点。例如:

select AVG(salary)
from employees
group by department_id
order by avg(salary) desc
limit 1

limit 1可能是top 1(SQL Server) 或rownum = 1(Oracle)的子查询。

于 2013-06-10T18:12:30.000 回答
1

It's dependent on RDBMS support, but if it is supported you'll get the largest of the departmental averages for the salary.

The group by is applied to the inner aggregate, and the outer aggregate is ungrouped.

于 2013-06-10T18:05:06.993 回答