欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

LeetCode——Nth Highest Salary

程序员文章站 2023-01-16 11:39:48
此题相较于 做了一些改进: 创建 ; 需要判断传入参数的合理性. 因此,对代码改动如下所示: mysql CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT BEGIN DECLARE P INT DEFAULT N 1; IF (P ......
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.

+------------------------+
| getnthhighestsalary(2) |
+------------------------+
| 200                    |
+------------------------+

此题相较于second highest salary做了一些改进:

  • 创建mysql function;
  • 需要判断传入参数的合理性.

因此,对代码改动如下所示:

create function getnthhighestsalary(n int) returns int
begin
  declare p int default n-1;
  if (p<0) then
    return null;
  else
  return (
      # write your mysql query statement below.
      select ifnull(
            (
                select distinct salary 
                from employee 
                order by salary desc 
                limit p,1)
            ,null)
          as secondhighestsalary   
  );
  end if;
end