Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shortening nested SQL Query

List the names of employees whose salary is greater than the average salary of the department in which the given employee works.

I have came out with the following solution: column names are: emp_id, name, dept, salary in the table named employee.

select name from employee
where salary >
(
select avg(salary) from employee
where dept= (select dept from employee where emp_id = 'a10')
) 
and
dept = (select dept from employee where emp_id = 'a10')
;

Can i make this a little shorter query, expecting the same result?

like image 638
Gopal Avatar asked Jun 11 '26 15:06

Gopal


1 Answers

This query is Oracle specific, but it has the advantage of only hitting the employee table once:

select name from 
   (select name, 
           salary, 
           avg(salary) over (partition by dept) as avg_salary 
      from employee)
where salary > avg_salary;
like image 70
Allan Avatar answered Jun 14 '26 06:06

Allan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!