1. 程式人生 > >176. 第二高的薪水

176. 第二高的薪水

沒有 The 臨時 pro use 如果 ng-if ifnull highest

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                 |
+---------------------+

編寫一個 SQL 查詢,獲取 Employee 表中第二高的薪水(Salary) 。

+----+--------+
| Id | Salary |
+----+--------+
| 1  | 100    |
| 2  | 200    |
| 3  | 300    |
+----+--------+

例如上述 Employee

表,SQL查詢應該返回 200 作為第二高的薪水。如果不存在第二高的薪水,那麽查詢應返回 null

+---------------------+
| SecondHighestSalary |
+---------------------+
| 200                 |
+---------------------+

方法1:使用子查詢和LIMIT子句

算法:按降序對不同的工資進行排序,然後利用該LIMIT子句獲得第二高的工資。

1 SELECT DISTINCT
2     Salary AS SecondHighestSalary
3 FROM
4 Employee 5 ORDER BY Salary DESC 6 LIMIT 1 OFFSET 1

但是,如果沒有這樣的第二高薪,這個解決方案將被判定為“錯誤答案”,因為此表中可能只有一條記錄。為了解決這個問題,我們可以將其作為臨時表。

1 SELECT
2     (SELECT DISTINCT
3             Salary
4         FROM
5             Employee
6         ORDER BY Salary DESC
7         LIMIT 1 OFFSET 1) AS SecondHighestSalary
8 ;



方法2:使用IFNULLLIMIT子句

解決‘NULL‘問題的另一種方法是使用IFNULL如下功能。

1 SELECT
2     IFNULL(
3       (SELECT DISTINCT Salary
4        FROM Employee
5        ORDER BY Salary DESC
6         LIMIT 1 OFFSET 1),
7     NULL) AS SecondHighestSalary

176. 第二高的薪水