i have a table called employees which i have name, department_id and salary in it. I want to find the employees whose salary is greater than the average of their department and see their names, department_id, salary and the average salary of their department. I have written this code but it does not work. How can we fix this? Thanks in advance.
SELECT name, department_id, salary, avg(salary)
FROM employees
GROUP BY name, department_id, salary
HAVING salary > (select avg(salary) from employees group by department_id)
I have updated my code as you said like:
SELECT department_id, salary, avg(salary), count(*)
FROM employees e
GROUP BY department_id, salary
HAVING salary > (select avg(salary) from employees e2 where e2.department_id=e.department_id)
But when i run this i get this result:
You can see that salary and the averages are the same and there are 2 department 80's, i need 1 of all the existing departments. How can we fix this. I am using the Oracle database if that's any important. Thanks.
Your code is quite close. But, instead of a group by
in the subquery, it needs to be correlated to the outer query. And, you don't need an outer aggregation, just a where
clause:
SELECT name, department_id, salary
FROM employees e
WHERE salary > (select avg(salary) from employees e2 where e2.department_id = e.department_id);
However, you are presumably learning Oracle. You can also write this query using analytic functions:
select e.*
from (select e.*, avg(salary) over (partition by department) as avgsalary
from employees e
) e
where e.salary > e.avgsalary;
Although this is probably a bit advanced for what you are learning, I encourage you to understand both queries.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With