设为首页 加入收藏

TOP

LeetCode——Nth Highest Salary
2019-10-09 20:05:00 】 浏览:50
Tags:LeetCode 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                    |
+------------------------+

此题相较于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
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇数据库系统学习(一) 下一篇SQL With As 用法

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目