我有下表:
并执行以下查询
select distinct lastname, firstname, max(salary) as salary
from employees
where salary not in (select max(salary) from employees)
group by lastname, firstname
我得到以下结果:
我想找到薪水第二高的员工的所有姓名,在给定的表中,这些员工都是6000薪水,但我能找到的唯一答案就是上面的查询。我现在正在寻找另一种方式,但我无法找到任何东西。
我正在使用SQL Server。有没有人有任何建议?
答案 0 :(得分:4)
您可以使用dense_rank()
窗口功能:
select * from (
select employees.*, dense_rank() over(order by salary desc) rnk from employees
) t
where rnk = 2
答案 1 :(得分:2)
如果您使用的是Sql Server 2005或更高版本,则可以使用DENSE_RANK。
with a as(
select lastname,firstname,salary,
dense_rank()over(order by salary desc)r
from employees
)
select lastname,firstname,salary
from a where r=2;
答案 2 :(得分:0)
您可以尝试下面的Sql查询
DECLARE @SecondHighestSalary Int
SELECT TOP 1 @SecondHighestSalary = salary FROM (
SELECT TOP 2 salary
FROM employees
ORDER BY salary DESC) AS emp
ORDER BY salary ASC
SELECT * FROM employees where salary = @SecondHighestSalary
您可以尝试以此获得第n个最高薪水,其中n = 1,2,3 ....(int)
SELECT TOP 1 salary FROM (
SELECT TOP n salary
FROM employees
ORDER BY salary DESC) AS emp
ORDER BY salary ASC
希望这会对您有所帮助。