zoukankan      html  css  js  c++  java
  • 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
    

    PS:
    如果您觉得我的文章对您有帮助,请关注我的微信公众号,谢谢!
    程序员打怪之路

  • 相关阅读:
    HBase 超详细介绍
    写在之前
    【CF】38E Let's Go Rolling! (dp)
    [CF] E. Camels
    CF9D How many trees? (dp)
    [CF] 8C Looking for Order
    CF dp 题(1500-2000难度)
    NOIP原题板刷
    Codeforces Round #595 (Div. 3) 题解
    CSP-S2019 停课日记
  • 原文地址:https://www.cnblogs.com/createwell/p/14149835.html
Copyright © 2011-2022 走看看