寻找我正在使用的第n个最高薪水
select salary from
(
select distinct ROW_NUMBER() over (order by salary desc) as rownum,Salary
from Employee
)a
where rownum=2
但是,如果我有相同的工资,如
70000
70000
60000
50000
50000
执行查询时,我获得第二高薪
70000 instead 60000
如何避免重复?
答案 0 :(得分:3)
这是必须明确的工资,而不是行数:
SELECT salary FROM
(
SELECT ROW_NUMBER() OVER (ORDER BY salary DESC) AS rownum, salary
FROM (SELECT DISTINCT Salary FROM Employee) T1
) T2
WHERE rownum=2
答案 1 :(得分:3)
虽然Mark已经提供了一个答案,但我会说你使用了错误的功能。你不想要行号,你想要RANK。根据您希望如何处理重复项,特别是您应该使用DENSE_RANK。
E.g:
SELECT salary FROM
(
SELECT DENSE_RANK() OVER (ORDER BY salary DESC) AS rank, salary
FROM Employee
) T2
WHERE rank=2
答案 2 :(得分:0)
这是使用CTE(公用表格表达)
找到第n个最高值With Result as
(
select salary ,DENSE_RANK () over(ORDER BY salary DESC) AS Denserank FROM employees
)
select Top 1 salary
FROM Result
where Result. Denserank=2