Suk*_*uAD 2 sql t-sql sql-server sql-server-2012
编写SQL查询以从Employee表中获得第n个最高薪水(SQL Server)
| Id | Salary |
+----+--------+
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
Run Code Online (Sandbox Code Playgroud)
对于此示例,n = 2的第n个最高薪水是200.如果没有第n个最高薪水,则查询应返回null.
| getNthHighestSalary(2) |
+------------------------+
| 200 |
Run Code Online (Sandbox Code Playgroud)
除了使用函数之外,有没有办法编写这个查询?
另一种可能的方法是使用ROW_NUMBER()或DENSE_RANK()函数.重要的是要知道在第N个职位或之前是否可以有多于一个薪水.
CREATE TABLE #Salary (
[id] int,
[salary] numeric(10, 2)
)
INSERT #Salary
([id], [salary])
VALUES
(1, 100),
(2, 500),
(3, 200),
(4, 300),
(5, 200);
DECLARE @Position int = 2;
-- With possible duplicate salaries
WITH cte AS (
SELECT
[id], [salary],
DENSE_RANK() OVER (ORDER BY [salary] ASC) AS [DRPosition]
FROM #Salary
)
SELECT [id]
FROM cte
WHERE [DRPosition] = @Position
ORDER BY [DRPosition];
-- Without possible duplicate salaries
WITH cte AS (
SELECT
[id], [salary],
ROW_NUMBER() OVER (ORDER BY [salary] ASC) AS [RPosition]
FROM #Salary
)
SELECT [id]
FROM cte
WHERE [RPosition] = @Position
ORDER BY [RPosition]
Run Code Online (Sandbox Code Playgroud)
以下内容几乎完全符合您的要求:
select salary
from employee
order by salary desc
offset <n> rows fetch next 1 row only;
Run Code Online (Sandbox Code Playgroud)
NULL唯一的问题是,没有这个薪水的时候,是不返回的。您可以使用子查询来处理:
select (select salary
from employee
order by salary desc
offset <n> rows fetch next 1 row only
) as salary;
Run Code Online (Sandbox Code Playgroud)
如果您希望关系具有相同的排名,请select distinct salary在子查询中使用。