码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode——Nth Highest Salary

时间:2019-10-09 09:20:45      阅读:77      评论:0      收藏:0      [点我收藏+]

标签:limit   pre   you   ret   sel   null   mysq   改进   where   

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                    |
+------------------------+

此题相较于Second Highest Salary做了一些改进:

  • 创建mysql function;
  • 需要判断传入参数的合理性.

因此,对代码改动如下所示:

CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
  DECLARE P INT DEFAULT N-1;
  IF (P<0) THEN
    RETURN NULL;
  ELSE
  RETURN (
      # Write your MySQL query statement below.
      SELECT IFNULL(
            (
                SELECT DISTINCT Salary 
                FROM Employee 
                ORDER BY Salary DESC 
                LIMIT P,1)
            ,NULL)
          AS SecondHighestSalary   
  );
  END IF;
END

LeetCode——Nth Highest Salary

标签:limit   pre   you   ret   sel   null   mysq   改进   where   

原文地址:https://www.cnblogs.com/jason1990/p/11639402.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!