SQL Server 每日一题--解析老N的收入

2020-09-08 16:38:11 浏览数 (1)

这个提的解题思路和老二那道题的思路一样,利用 row_number 解决

零、解析

首先去除数据中相同的工资,然后将工资从大到小排序,接着利用 row_number 函数给每行数据加上行号,最后过滤出行号为N的工资,因为需要根据指定的排名查询,因此这里用到了函数。代码如下:

代码语言:javascript复制
CREATE FUNCTION getNthHighestSalary(@N INT) RETURNS INT AS
BEGIN

    RETURN (
        /* Write your T-SQL query statement below. */
        select NULLIF((select Salary from (select Salary,row_number() over(order by Salary desc) as rn from (select distinct Salary from Employee)as e) as demo where rn=@N),null) as SecondHighestSalary
    );
END

0 人点赞