我正在用 SQL 编写这个查询:
select MAX(AVG(salary) ) from employees group by department_id;
首先我会得到分组department_id
,但接下来会发生什么?
我正在用 SQL 编写这个查询:
select MAX(AVG(salary) ) from employees group by department_id;
首先我会得到分组department_id
,但接下来会发生什么?
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;
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
你可以通过只获得一排来做到这一点。例如:
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)的子查询。
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.