我有工资表,我想找到第二大工资记录,第三大工资记录等等。 要检索第二大记录,我使用以下查询
Select Top 1 * from SalaryTable
where salary < (Select Max(Salary) from SalaryTable)
order by Salary desc
同样,我怎样才能找到第三大唱片或第四大唱片等等?有没有办法检索特定记录?
答案 0 :(得分: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)
答案 1 :(得分:3)
使用RANK()函数
SELECT *
FROM
(SELECT *
,RANK() OVER (ORDER BY salary) AS SalRnk
FROM SalaryTable) AS tblSal
WHERE tblSal.SalRnk = 2 -- for second highest record. change this value to 1,2,3,4 etc... for various rank records
答案 2 :(得分: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 :(得分:0)
您可以输入任何值而不是n,它会为您提供所需的最高薪水。
select top 1 salary
from(Select Distinct top n salary from Salary order by desc)a
order by salary Asc