1.  题目来源:

第N高的薪水

2.  具体题目:

数据表:Employee表,字段为id,salary

查询条件:获取Employee表中第n高的薪水,如果不存在,则查询返回null。

3.  思路:

本题主要考察的是SQL语言中自定义函数的使用

  • 声明局部变量(作用范围在begin到end语句块之间,不用加@)
  • set语句对变量赋值
  • 自定义函数

4.  具体操作:

# 创建函数之前需要制定一个参数
set global log_bin_trust_function_creators=TRUE;

# 创建函数
CREATE FUNCTION getNthHighestSalary(n INT) RETURNS INT
BEGIN
   DECLARE s INT; 
   SET s = n-1;
   RETURN(
       select IFNULL((select distinct Salary from Employee1 order by  Salary desc limit s, 1), null) as getNthHighestSalary
         );
END;

# 调用自定义函数
SELECT getNthHighestSalary(2);

查询结果:

LeetCode题库 - 第N高的薪水

 

相关文章:

  • 2021-05-16
  • 2022-12-23
  • 2021-08-13
  • 2022-12-23
  • 2022-01-12
  • 2021-08-25
  • 2021-12-04
  • 2022-01-04
猜你喜欢
  • 2021-07-26
  • 2022-12-23
  • 2021-08-03
  • 2021-11-08
  • 2021-08-05
  • 2021-12-28
  • 2022-12-23
相关资源
相似解决方案