Leetcode_Database-177. Nth Highest Salary

#Leetcode Database

177. Nth Highest Salary

URL: https://leetcode.com/problems/nth-highest-salary/

Write a SQL query to get the nth highest salary from the Employee table.

+----+--------+
| Id | Salary |
+----+--------+
| 1  | 100    |
| 2  | 200    |
| 3  | 300    |
+----+--------+

For example, given the above Employee table, the nth highest salary where n = 2 is 200. If there is no nth highest salary, then the query should return null.

+------------------------+
| getNthHighestSalary(2) |
+------------------------+
| 200                    |
+------------------------+

这个题跟176. Second Highest Salary 方法类似,只是将查询过程写到了一个函数中,用了 CREATE FUNCTION

【Solution 1】:

CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
    DECLARE  tmp_N INT;  //声明一个变量tmp_N
    SET tmp_N = N-1;   // 因为之后用到 limit... offset ..从取第Nth最高的工资,所以从第N-1行开始
    Return(
        Select DISTINCT Salary
        From Employee order by Salary Desc 
        limit 1 Offset tmp_N);
END


【Soultion 2】: 

CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
    Return(
    SELECT Salary  
    FROM (SELECT Distinct Salary, DENSE_RANK() OVER ( ORDER BY Salary DESC my_rank FROM  Employee) AS tmp WHERE my_rank = N
    );
END

 

【Note】:

LIMIT n1 OFFSET n2  从第n2行开始(不包含n2)取n1行数据

eg: Select * from student limit 3 offset 10    从第10行开始往下去3行,即 11,12,13行的数据

RANK() OVER()DENSE_RANK() OVER()

RANK() OVER( ORDER BY 排序的字段名) :    如果出现并列情况,则排名相同,下一个数据排名延后。那么 排名的数字顺序为不连续。

eg 成绩排名,100 为 Rank = 1, 99,99出现两次,RANK均为2, 下一个96,RANK = 4。 (RANK=3的情况不会显示)RANK的数字非连续。

 

DENSE_RANK() OVER(ORDER BY 排序的字段名)  区别在于 在并列情况下,RANK的数字连续,

eg 成绩排名,100 为 Rank = 1, 99,99出现两次,RANK均为2, 下一个96,RANK = 3。 (RANK=3的情况不会显示)RANK的数字连续。

 

CREATE FUNCTION 用法:

语句如下:

CREATE FUNCTION function_name [ (parameter datatype [, parameter datatype]) ] RETURNS return_datatype

BEGIN

   declaration_section //声明变量

   executable_section  

END;

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值