Oracle show all employees with greater than average salary of their department

后端 未结 4 799
离开以前
离开以前 2020-12-11 23:02

I am writing a query to find employees who earn greater than the average salary within their department. I need to display the employee ID, salary, department id, and averag

4条回答
  •  感动是毒
    2020-12-11 23:27

    I don't believe you can refer to a column alias (avg_sal in this case) in a WHERE clause.

    You'll need to repeat that inner query, i.e.:

    SELECT employee_id, salary, department_id,
      (SELECT ROUND(AVG(salary),2)
      FROM employees e_inner
      WHERE e_inner.department_id = e.department_id) AS avg_sal
    FROM employees e
    WHERE salary > 
     (SELECT ROUND(AVG(salary),2)
      FROM employees e_inner
      WHERE e_inner.department_id = e.department_id)
    ORDER BY avg_sal DESC
    

    Not great, with those two inner queries, but that's the most-straightforward way to correct the error.

    Update: Haven't tested this, but try the following:

    SELECT e.employee_id, e.salary, e.department_id, b.avg_sal
    FROM employees e
    INNER JOIN
    (SELECT department_id, ROUND(AVG(salary),2) AS avg_sal
     FROM employees
     GROUP BY department_id) e_avg ON e.department_id = e_avg.department_id AND e.salary > e_avg.avg_sal
    ORDER BY e_avg.avg_sal DESC
    

提交回复
热议问题