▌題目描述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