LeetCode (177): N-high salaries Reformat Department Table (SQL)

2020.1.12 LeetCode personal notes from scratch single brush finish (continually updated)

github:https://github.com/ChopinXBP/LeetCode-Babel

Portal: reformatting the department table

Write a SQL query to get the Employee table in the n-th high salary (Salary).

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

Employee table above example, n = 2, the second high salary should return 200. If the n-th high salary does not exist, then the query should return null.

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


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


#Coding one hour, Copying one second. Leave a message point a praise chant, thank you #

Published 246 original articles · won praise 316 · views 30000 +

Guess you like

Origin blog.csdn.net/qq_20304723/article/details/103945080