176. Second Highest Salary SQL查詢語句中的 limit offset
阿新 • • 發佈:2018-11-22
題目:
Write a SQL query to get the second highest salary from the Employee table
Id | Salary ---|--- 1 | 100 2 | 200 3 | 300
For example, given the above Employee table, the query should return 200 as the second highest salary. If there is no second highest salary, then the query should return null.
-
SecondHighestSalary 200
Wrong answer: 只有一條記錄時報錯
SELECT DISTINCT
Salary AS SecondHighestSalary
FROM
Employee
ORDER BY Salary DESC
LIMIT 1 OFFSET 1
answer1: 將Wrong answer的查詢結果作為temp表
SELECT (SELECT DISTINCT Salary FROM Employee ORDER BY Salary DESC LIMIT 1 OFFSET 1) AS SecondHighestSalary
answer2: Using IFNULL
SELECT
IFNULL(
(SELECT DISTINCT
Salary
FROM
Employee
ORDER BY Salary DESC
LIMIT 1 OFFSET 1),
NULL) AS SecondHighestSalary
相關知識點
SQL查詢語句中的 limit offset
① selete * from testtable limit 2,1;
② selete * from testtable limit 2 offset 1;
注意:
1.資料庫資料計算是從0開始的
2.offset X是跳過X個數據,limit Y是選取Y個數據
3.limit X,Y 中X表示跳過X個數據,讀取Y個數據
這兩個都是能完成需要,但是他們之間是有區別的:
①是從資料庫中第三條開始查詢,取一條資料,即第三條資料讀取,一二條跳過
②是從資料庫中的第二條資料開始查詢兩條資料,即第二條和第三條。