[LeetCode] Nth Highest Salary 第N高薪水 LeetCode All in One 题目讲解汇总(持续更新中...)

 

Write a SQL query to get the nth highest salary from the Employee table.html

+----+--------+
| 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.post

 

这道题是以前那道Second Highest Salary的拓展,根据以前那道题的作法,咱们能够很容易的将其推展为N,根据对Second Highest Salary中解法一的分析,咱们只须要将OFFSET后面的1改成N-1就好了,可是这样MySQL会报错,估计不支持运算,那么咱们能够在前面加一个SET N = N - 1,将N先变成N-1再作也是同样的:url

 

解法一:spa

CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
  SET N = N - 1;
  RETURN (
      SELECT DISTINCT Salary FROM Employee GROUP BY Salary
      ORDER BY Salary DESC LIMIT 1 OFFSET N
  );
END

 

根据对Second Highest Salary中解法四的分析,咱们只须要将其1改成N-1便可,这里却支持N-1的计算,参见代码以下:code

 

解法二:htm

CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
  RETURN (
      SELECT MAX(Salary) FROM Employee E1
      WHERE N - 1 =
      (SELECT COUNT(DISTINCT(E2.Salary)) FROM Employee E2
      WHERE E2.Salary > E1.Salary)
  );
END

 

固然咱们也能够经过将最后的>改成>=,这样咱们就能够将N-1换成N了:blog

 

解法三:leetcode

CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
  RETURN (
      SELECT MAX(Salary) FROM Employee E1
      WHERE N =
      (SELECT COUNT(DISTINCT(E2.Salary)) FROM Employee E2
      WHERE E2.Salary >= E1.Salary)
  );
END

 

相似题目:get

Second Highest Salaryit

 

参考资料:

https://leetcode.com/discuss/88875/simple-answer-with-limit-and-offset

https://leetcode.com/discuss/63183/fastest-solution-without-using-order-declaring-variables

 

LeetCode All in One 题目讲解汇总(持续更新中...)

相关文章
相关标签/搜索