Skip to content

Commit 227c07f

Browse files
authored
Add files via upload
1 parent 0bbac45 commit 227c07f

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
---
2+
title: LeetCode-176. Second Highest Salary
3+
date: 2017-11-07 14:22:31
4+
tags: [LeetCode,mysql]
5+
permalink: leetcode-second-height-salary
6+
copyright: true
7+
password:
8+
top:
9+
---
10+
11+
Write a SQL query to get the second highest salary from the `Employee` table.
12+
<!-- more -->
13+
14+
```
15+
+----+--------+
16+
| Id | Salary |
17+
+----+--------+
18+
| 1 | 100 |
19+
| 2 | 200 |
20+
| 3 | 300 |
21+
+----+--------+
22+
```
23+
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`.
24+
```
25+
+---------------------+
26+
| SecondHighestSalary |
27+
+---------------------+
28+
| 200 |
29+
+---------------------+
30+
```
31+
**思路:**
32+
  按薪水`salary` 倒序排序,然后从第一个开始,取下一个。
33+
  
34+
**一开始我的SQL(`Wrong Answer`)**
35+
```
36+
SELECT DISTINCT Salary as SecondHighestSalary
37+
FROM Employee
38+
ORDER BY Salary DESC
39+
LIMIT 1 OFFSET 1
40+
```
41+
忽略了如果表中`salary`的值只有一种的情况,这样就没有`the second highest salary`,输出 `null`.
42+
**正确写法:**
43+
```
44+
SELECT IFNULL(
45+
(SELECT DISTINCT Salary
46+
FROM Employee
47+
ORDER BY Salary DESC
48+
LIMIT 1 OFFSET 1),
49+
NULL) AS SecondHighestSalary
50+
```
51+
**IFNULL**
52+
  这儿用到了 MySQL 的 `IFNULL(expr1,expr2)`函数,如果 expr1 不是 NULL,IFNULL() 返回 expr1,否则它返回 expr2。
53+
  
54+

0 commit comments

Comments
 (0)