Oracle Show All Employees With Greater Than Average Salary Of Their Department
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 average salar
Solution 1:
More efficient to use analytics:
select employee_id, salary, department_id, avg_sal
from
(
SELECT employee_id, salary, department_id,
round(avg(salary) over (partitionby department_id), 2) avg_sal
from emp
)
where salary > avg_sal
orderby avg_sal descSolution 2:
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)
ORDERBY avg_sal DESCNot 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
GROUPBY department_id) e_avg ON e.department_id = e_avg.department_id AND e.salary > e_avg.avg_sal
ORDERBY e_avg.avg_sal DESC
Solution 3:
You could rewrite it as a join:
SELECT e1.employee_id
, e1.salary
, e1.department_id
, ROUND(AVG(e2.salary),2) as Avg_Sal
FROM employees e
JOIN employees e2
ON e2.department_id = e.department_id
GROUPBY
e1.employee_id
, e1.salary
, e1.department_id
HAVING e1.salary > ROUND(AVG(e2.salary),2)
Or a subquery:
SELECT *
FROM (
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
) as SubqueryAlias
WHERE salary > avg_sal
Solution 4:
select *
from employees e
join(
select Round(avg(salary)) AvgSal,department_id,department_name as dept_name
from employees join departments
using (department_id)
groupby department_id,department_name
) dd
using(department_id)
where e.salary > dd.AvgSal;
another solution
select *
from employees e,
(
select
department_id,
avg(salary) avg_sal
from employees
groupby department_id
) e1
where e.department_id=e1.department_id
and e.salary > e1.avg_sal
Post a Comment for "Oracle Show All Employees With Greater Than Average Salary Of Their Department"