2011-05-10 87 views
0

我有工資表,是否想找到第二大薪水記錄,第三大薪水記錄等等。 要檢索我使用下面的查詢正在檢索第n個記錄

Select Top 1 * from SalaryTable 
    where salary < (Select Max(Salary) from SalaryTable) 
    order by Salary desc 

同樣第二大紀錄,我怎麼能找到第三大紀錄或第四大記錄等?有沒有辦法檢索特定的記錄?

回答

1
SELECT TOP 1 salary 
FROM (
SELECT DISTINCT TOP n salary 
FROM employee 
ORDER BY salary DESC) a 
ORDER BY salary 
where n > 1 (n is always greater than one) 
3

你可以開始使用RANK() function in SQL Server

;WITH CTE AS 
(
SELECT ..., RANK() OVER (ORDER BY emp_salary) AS rn 
FROM myTable 
) 
SELECT ... 
FROM CTE 
WHERE rn = n -- (value of should be replace with numberic number for ex. 1, 2, 3) 
0

你可以把任何值,而不是N,它給你所需的最大薪水。

select top 1 salary 
from(Select Distinct top n salary from Salary order by desc)a 
order by salary Asc