SQL查询不成功

时间:2014-03-21 19:32:09

标签: sql

我需要在基本的部门员工表中找到以下内容 sql员工工资高于部门平均工资的每个部门薪水最低的员工是什么 我得到的是这个:

     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
)

我得到的结果大于平均值而不是特定部门 即如果部门1的平均值为50且部门2的平均值为37,则我得到部门1的正确答案,但部门2的答案为75,而部门2的员工则为40

1 个答案:

答案 0 :(得分:1)

  1. 选择员工每个部门的avarage工资。
  2. 与员工一起,找到最低工资,而不是每个部门的平均工资。
  3. 再次与员工联系,让所有员工在其所在部门获得该薪水。
  4. 以下是声明:

    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;