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 |
+------------------------+
這條題目接觸到了一個(gè)新的概念:SQL函數(shù)。關(guān)于MySQL中函數(shù)的概念和含義這里先不詳解,有興趣的碼友可以去別的大牛博客看看。
對于題目的要求,可以得出的分析如下:
1.獲得salary字段排第n位的記錄,這里的排名需要去重,要用到distinct關(guān)鍵字來去重。
2.僅獲得一條記錄,需要用到limit關(guān)鍵字。注意的一點(diǎn),limit關(guān)鍵字的參數(shù)是從第n條記錄開始(不包括第n條),到第n+m條記錄。即,第一個(gè)參數(shù)是上標(biāo),第二個(gè)參數(shù)是偏移量。在這個(gè)題目里面,獲得第n個(gè)記錄的語法是
limit n-1, 1
但是因?yàn)閟ql中不能嵌入n-1這種表達(dá)式,所以要在函數(shù)體中通過declare和set關(guān)鍵字來保存n-1的值。
最后的語句如下:
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
declare n1 int;
set n1=N-1;
RETURN (
SELECT distinct salary from employee ORDER BY salary DESC LIMIT n1,1
);
END