如何获得薪酬最高的员工队伍

时间:2011-08-31 19:35:02

标签: sql-server tsql sql-server-2008 greatest-n-per-group

表格包括员工姓名,地址,电话,部门,薪水:

如何从每个部门获得收入最高的员工行?

我试过

select dept, max(salary) from employee group by dept

但它只提供两列。但我想选择一整行。怎么做?

或者如何在结果中添加更多列?

(我正在使用SQL Server 2008)

6 个答案:

答案 0 :(得分:10)

您只需将当前拥有的查询加入到employee表中即可获取完整的员工信息。

select e.*
from employee e
inner join (select dept, max(salary) ms from employee group by dept) m
  on e.dept = m.dept and e.salary = m.ms

答案 1 :(得分:5)

SELECT name,
       address,
       phone,
       department,
       salary,
       dept
FROM   (SELECT name,
               address,
               phone,
               department,
               salary,
               dept,
               row_number() OVER(PARTITION BY dept ORDER BY salary DESC) AS rn
        FROM   employee) AS e
WHERE  e.rn = 1  

如果最高薪水存在平局,则使用row_number()将为您提供一行。如果你想要每个部门的所有最高工资,你应该使用rank()代替。

SELECT name,
       address,
       phone,
       department,
       salary,
       dept
FROM   (SELECT name,
               address,
               phone,
               department,
               salary,
               dept,
               rank() OVER(PARTITION BY dept ORDER BY salary DESC) AS rn
        FROM   employee) AS e
WHERE  e.rn = 1

答案 2 :(得分:3)

with cte as (
  select *, rank() over (partition by dept order by salary desc) as [r]
  from employees
)
select * from cte where [r] = 1;

答案 3 :(得分:2)

这样的东西?

select * from employee where salary = (select max(salary) from employee)

答案 4 :(得分:1)

select * from employee 
where salary in
(select  max(salary) from employee group by dept);

答案 5 :(得分:0)

如果您在同一个表格中同时拥有员工详细信息和部门,并且您必须找到每个部门中收入最高的员工,如下所示

EmployeeId  EmployeeName    Department     Salary
1            Neeraj         Dot Net        45000
2            Ankit          Java           5000
3            Akshay         Java           6000
4            Ramesh         Dot Net        7600
5            Vikas          Java           4000
7            Neha           Php            8500
8            Shivika        Php            4500
9            Tarun          Dot Net        9500

然后您可以使用以下解决方案解决它

解决方案 - 1

SELECT t.EmployeeName,t.Department,t.Salary 
FROM(SELECT MAX(Salary) AS TotalSalary,Department FROM Employee GROUP BY Department) 
AS TempNew Inner Join Employee t ON TempNew.Department=t.Department  
and TempNew.TotalSalary=t.Salary 
ORDER BY t.Department ASC

解决方案-2

;WITH EmployeeDetails AS (
SELECT EmployeeName, Department, DENSE_RANK() OVER(PARTITION BY Department 
ORDER BY Salary DESC) AS SalaryRank, Salary FROM Employee )
SELECT EmployeeName, Department, Salary FROM EmployeeDetails WHERE SalaryRank=1

输出

EmployeeName    Department  Salary
Neeraj           Dot Net    45000
Akshay           Java       6000
Neha             Php        8500