8000 add : 176 · h-j-13/LeetCode-Database@26a3bc6 · GitHub
[go: up one dir, main page]

Skip to content

Commit 26a3bc6

Browse files
committed
add : 176
1 parent 98d01a1 commit 26a3bc6

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# LeetCode176. Second Highest Salary
2+
3+
# 题目
4+
Write a SQL query to get the second highest salary from the ```Employee``` table.
5+
```
6+
+----+--------+
7+
| Id | Salary |
8+
+----+--------+
9+
| 1 | 100 |
10+
| 2 | 200 |
11+
| 3 | 300 |
12+
+----+--------+
13+
```
14+
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.
15+
```
16+
+---------------------+
17+
| SecondHighestSalary |
18+
+---------------------+
19+
| 200 |
20+
+---------------------+
21+
```
22+
23+
题目大意 : 找出第二高的薪水
24+
25+
## 解题思路
26+
27+
首先很容易想到,先WHERE salary != 最高的薪水 然后在做排序 或者 取最大值就可获得第二高的薪水,但是若是第三 第N 高的薪水则要迭代此方法数次 造成效率下降,在只select 一次表的情况 排序后使用limit选择第N条记录 不失为一个更高效的选择
28+
29+
### LIMIT
30+
```sql
31+
SELECT Salary AS 'SecondHighestSalary' FROM Employee ORDER BY Salary DESC LIMIT 1,1;
32+
```
33+
![](http://upload-images.jianshu.io/upload_images/5617720-be6e1556f0609a31.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
34+
35+
结果在只有一条记录的时候出错了...
36+
37+
因为从第一条记录向下偏移了一条, 导致本该的null的变成了无结果
38+
再加一层select 筛选即可 因为 select 的无结果默认值为null
39+
最后别忘了加上DISTINCT 因为同一工资的人可能有很多
40+
41+
进行修改
42+
```sql
43+
SELECT (
44+
SELECT DISTINCT Salary AS 'SecondHighestSalary' FROM Employee ORDER BY Salary DESC LIMIT 1 OFFSET 1
45+
) AS 'SecondHighestSalary';
46+
```
47+

0 commit comments

Comments
 (0)
0