2010-09-03 60 views
0

對於查找第n個最高工資,我使用的SQL Server 2005/2008找到第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 

如何避免重複?

回答

3

儘管馬克已經提供了一個答案,我會說,你使用了錯誤的功能。你不想要行號,你想要的排名。根據你想如何處理重複,具體你應該使用DENSE_RANK

例如爲:

SELECT salary FROM 
(
    SELECT DENSE_RANK() OVER (ORDER BY salary DESC) AS rank, salary 
    FROM Employee 
) T2 
WHERE rank=2 
+0

謝謝達明爲你澄清後 – Gopi 2010-09-03 06:55:14

+0

+1我同意。這是做到這一點的正確方法。 – 2010-09-03 20:54:51

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 
0

這裏是發現第n個最高使用CTE(公共表表達式)

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