Database Leetcode 177 Nth Highest Salary

Database Leetcode 177 Nth Highest Salary

目录:

  1. 题目

  2. 解题思路

  3. 他山之石

1. 题目

 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.

2. 解题思路

先看自定义Function语法,关键在于定义N-1,limit初始值为0

CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
    SET N = N - 1;
  RETURN (
      # Write your MySQL query statement below.
      
     select ifnull((SELECT distinct(Salary) as Salary FROM Employee  ORDER BY Salary DESC LIMIT N,1 ) , null) Salary
  );
END

3. 他山之石

No Variable, No Limit X,1, Just one query, 808ms的奇淫技巧 anuarui

    CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
    
  RETURN (
      # Write your MySQL query statement below.
      
    
      SELECT e1.Salary
      FROM (SELECT DISTINCT Salary FROM Employee) e1
      WHERE (SELECT COUNT(*) FROM (SELECT DISTINCT Salary FROM Employee) e2 WHERE e2.Salary > e1.Salary) = N - 1      
      
      LIMIT 1
      
      
      
      
  );
END

标签: none

添加新评论