I am trying to display the maximum average salary; however, I can\'t seem to get it to work.
I can get a list of the average salaries to display with:
select worker_id, avgsal
from
(
select worker_id, avg(salary) as avgsal
from workers
group by worker_id
)
where avgsal=(select max(avgsal)
from (select worker_id, avg(salary) as avgsal
from workers group by worker_id))
This will display the highest average along with worker id
select worker_id, avg(salary)
from workers
group by worker_id
having avg(salary) = (select max(avgsal) from
(select worker_id, avg(salary) as avgsal
from workers
group by worker_id));
This should also work i guess
As explained here you can use
SELECT worker_id, AVG(salary)
FROM workers
GROUP BY worker_id
HAVING AVG(salary) = (SELECT MAX(AVG(salary)) FROM workers GROUP BY worker_id)
https://stackoverflow.com/a/8050885/12190487 shows the folllowing error
ER_DERIVED_MUST_HAVE_ALIAS: Every derived table must have its own alias
Use alias for the new formed column you are selecting from
select max(avg_salary)
from (select worker_id, avg(salary) AS avg_salary
from workers
group by worker_id) as avg ;
You can also do this with a single select
statement (combining both max
and avg
) like this
select max(avg(salary)) max_avg_salary
from workers
group by worker_id;
Columns resulting from aggregate functions (e.g. avg) usually get arbitrary names. Just use an alias for it, and select on that:
select max(avg_salary)
from (select worker_id, avg(salary) AS avg_salary
from workers
group by worker_id) As maxSalary;