Skip to content

Commit b06a48f

Browse files
committed
Add solution 177 [sql]
1 parent e0b9202 commit b06a48f

File tree

2 files changed

+81
-0
lines changed

2 files changed

+81
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,7 @@ Complete [solutions](https://github.com/doocs/leetcode/tree/master/solution) to
8787
| 144 | [Binary Tree Preorder Traversal](https://github.com/doocs/leetcode/tree/master/solution/144.Binary%20Tree%20Preorder%20Traversal) | `Stack`, `Tree` |
8888
| 150 | [Evaluate Reverse Polish Notation](https://github.com/doocs/leetcode/tree/master/solution/150.Evaluate%20Reverse%20Polish%20Notation) | `Stack` |
8989
| 153 | [Find Minimum in Rotated Sorted Array](https://github.com/doocs/leetcode/tree/master/solution/153.Find%20Minimum%20in%20Rotated%20Sorted%20Array) | `Array`, `Binary Search` |
90+
| 177 | [Nth Highest Salary](https://github.com/doocs/leetcode/tree/master/solution/177.Nth%20Highest%20Salary) | `SQL` |
9091
| 328 | [Odd Even Linked List](https://github.com/doocs/leetcode/tree/master/solution/328.Odd%20Even%20Linked%20List) | `Linked List` |
9192

9293

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
## 第N高的薪水
2+
### 题目描述
3+
4+
编写一个 SQL 查询,获取 `Employee` 表中第 n 高的薪水(Salary)。
5+
```
6+
+----+--------+
7+
| Id | Salary |
8+
+----+--------+
9+
| 1 | 100 |
10+
| 2 | 200 |
11+
| 3 | 300 |
12+
+----+--------+
13+
```
14+
15+
例如上述 `Employee` 表,n = 2 时,应返回第二高的薪水 `200`。如果不存在第 n 高的薪水,那么查询应返回 null。
16+
```
17+
+------------------------+
18+
| getNthHighestSalary(2) |
19+
+------------------------+
20+
| 200 |
21+
+------------------------+
22+
```
23+
24+
### 解法
25+
对 Salary 进行分组,然后根据 Salary 降序排列。选出偏移为 n-1 的一个记录即可。
26+
27+
```sql
28+
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
29+
BEGIN
30+
SET N = N - 1;
31+
RETURN (
32+
# Write your MySQL query statement below.
33+
select Salary from Employee group by Salary order by Salary desc limit 1 offset N
34+
);
35+
END
36+
37+
```
38+
39+
#### Input
40+
```json
41+
{
42+
"headers": {
43+
"Employee": [
44+
"Id",
45+
"Salary"
46+
]
47+
},
48+
"argument": 2,
49+
"rows": {
50+
"Employee": [
51+
[
52+
1,
53+
100
54+
],
55+
[
56+
2,
57+
200
58+
],
59+
[
60+
3,
61+
300
62+
]
63+
]
64+
}
65+
}
66+
```
67+
68+
#### Output
69+
```json
70+
{
71+
"headers": [
72+
"getNthHighestSalary(2)"
73+
],
74+
"values": [
75+
[
76+
200
77+
]
78+
]
79+
}
80+
```

0 commit comments

Comments
 (0)