此題相較於 做了一些改進: 創建 ; 需要判斷傳入參數的合理性. 因此,對代碼改動如下所示: 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