Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested aggregate functions, Max(Avg()), in SQL [closed]

Tags:

sql

I'm writing this query in SQL :

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

First I will get groups by department_id , but next what will happen ?

like image 593
Ala Aga Avatar asked Jun 10 '13 18:06

Ala Aga


Video Answer


1 Answers

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;
like image 62
Nikola Mitev Avatar answered Oct 05 '22 18:10

Nikola Mitev