Moutabreath
Moutabreath

Reputation: 196

Sql query unsuccessful

I have employee and department tables. I need to find the following SQL query:

What is the employee with the lowest salary for each department where the employees salary is greater than the average salary for the department.

I tried this:

     select * from [Company Management].[dbo].[Employee]
       where Salary in
       (select min(Salary) from [Company Management].[dbo].[Employee]
         where salary>=All
       --average  employee salary for department
         (select avg(salary) from [Company Management].[dbo].[Employee]
           group by DepartmentID)
         group by DepartmentID)

What I get in the result is greater than both averages and not department specific. i.e. if the average for department 1 is 50 and for department 2 is 37 I get correct answer for department 1 but 75 for department two, and department 2 has an employee with 40.

Upvotes: 0

Views: 74

Answers (1)

Thorsten Kettner
Thorsten Kettner

Reputation: 94913

  1. Select avarage salaries per department in employees.
  2. Join with employees and find thus the minimum salary higer than the avarage salary per department.
  3. Join again with employees to get all employees having that salary in their department.

Here is the statement:

select employee.*
from employee
join
(
  select employee.departmentid, min(employee.salary) as sal
  from employee
  join
  (
    select departmentid, avg(salary) 
    from employee 
    group by departmentid
  ) avg_sals on avg_sals.departmentid = employee.departmentid and avg_sals.salary < employee.salary
  group by employee.departmentid
) wanted_sals on wanted_sals.departmentid = employee.departmentid and wanted_sals.sal = employee.salary;

Upvotes: 1

Related Questions