1. 程式人生 > 其它 >【SQL】LeetCode-Nth Highest Salary

【SQL】LeetCode-Nth Highest Salary

技術標籤:SQL

LeetCode 177:Nth Highest Salary

【Description】

Write a SQL query to get the nth highest salary from the Employee table.
在這裡插入圖片描述
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.
在這裡插入圖片描述

【Solution】

CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
  SET N=N-1;
  RETURN (
      # Write your MySQL query statement below.
        IFNULL(
            (SELECT DISTINCT Salary
             FROM Employee
             ORDER BY Salary DESC
             LIMIT 1 OFFSET N),
             NULL)
  );
END