如何从每个部门检索员工的最高工资

时间:2014-05-05 21:10:32

标签: sql sql-server-2008

考虑表Employee:

Department number      Employee_id      Salary
   1                       123           2000
   1                       234           3266
   1                       657           3265
   2                       546           2050
   2                       657           3000
   2                       121           6000
   3                       131           6500
   3                       141           5000
   3                       151           1050

现在我想检索每个部门薪水最高的employee_id。如何为此编写查询?

3 个答案:

答案 0 :(得分:1)

处理这些查询的好方法是使用row_number()

select department_number, employee_id, salary
from (select e.*, row_number() over (partition by department order by salary desc) as seqnum
      from employee e
     ) e
where seqnum = 1;

如果您想在有关系时为部门获取多行,请使用dense_rank()rank()代替row_number()

答案 1 :(得分:0)

试试这个

SELECT Dept_Num,EmpID,Salary
from Employee
WHERE Salary IN (Select MAX(Salary) from Employee Group By Dept_Num)

答案 2 :(得分:-3)

您可以使用 max 语句:

Select departament_number,employee_id,salary
from employee
where salary in (select MAX(salary) from employee group by departament_number)