177. Nth Highest Salary

末蓝、 2022-04-24 14:58 237阅读 0赞
  1. Write a SQL query to get the nth highest salary from the Employee table.
  2. +----+--------+
  3. | Id | Salary |
  4. +----+--------+
  5. | 1 | 100 |
  6. | 2 | 200 |
  7. | 3 | 300 |
  8. +----+--------+
  9. 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.
  10. +------------------------+
  11. | getNthHighestSalary(2) |
  12. +------------------------+
  13. | 200 |
  14. +------------------------+

此题与上一题大同小异。代码如下:

  1. CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
  2. BEGIN
  3. DECLARE M INT;
  4. SET M=N-1;
  5. RETURN (
  6. # Write your MySQL query statement below.
  7. Select
  8. (Select Distinct Salary
  9. From Employee
  10. Order By Salary Desc
  11. Limit 1 Offset M) AS N_th_HighestSalary
  12. );
  13. END

发表评论

表情:
评论列表 (有 0 条评论,237人围观)

还没有评论,来说两句吧...

相关阅读