Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Employees with higher salary than their department average? [duplicate]

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:

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.

like image 623
Solijoli Avatar asked Aug 10 '14 14:08

Solijoli


1 Answers

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.

like image 128
Gordon Linoff Avatar answered Jun 12 '23 10:06

Gordon Linoff