▌题目描述app
Write a SQL query to get the nth highest salary from the
Employee
table.ide
写一段SQL查询语句,以获得Employee表中第n个高的工资。函数
+----+--------+ | 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 returnnull
.spa
例如,给定以上Employee表,第2高的工资就是200。若是没找到第n个高的公司,查询须要返回null。code
+------------------------+ | getNthHighestSalary(2) | +------------------------+ | 200 | +------------------------+
▌参考答案orm
题中已经写好了一个函数,咱们须要将查询的SQL语句写在注释下面,而后返回结果。
ci
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
RETURN (
# Write your MySQL query statement below.
);
END
参考1:get
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
DECLARE M INT;
SET M=N-1;
RETURN (
# Write your MySQL query statement below.
SELECT DISTINCT Salary
FROM Employee
ORDER BY Salary DESC LIMIT M, 1
);
END
▌答案解析it
参考1table
查找第n高的工资,咱们很天然的想到了LIMIT的用法。
LIMIT X,Y含义:X表示跳过X个数据,Y表示选取Y个数据。
或者使用 LIMIT Y OFFSET X,也是同样的效果。
若是想要获得第n高的工资,那么就须要跳过前面n-1个数据。所以,咱们直接写成下面这样:
SELECT DISTINCT Salary
FROM Employee
ORDER BY Salary DESC LIMIT N-1, 1
可是这样写是有语法错误的,SQL语句没法执行。所以咱们绕过这种错误写法,而在前面定义一个新的变量M,它的值为N-1,这样就能够完美解决了。
DECLARE M INT;
SET M=N-1;
因此,最终的完整代码以下:
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
DECLARE M INT;
SET M=N-1;
RETURN (
# Write your MySQL query statement below.
SELECT DISTINCT Salary
FROM Employee
ORDER BY Salary DESC LIMIT M, 1
);
END