Skip to content

Commit 452d05b

Browse files
committed
Add solution 177 [sql]
Rank Scores
1 parent 37456a2 commit 452d05b

File tree

2 files changed

+117
-0
lines changed

2 files changed

+117
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,7 @@ Complete [solutions](https://github.com/doocs/leetcode/tree/master/solution) to
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` |
9090
| 177 | [Nth Highest Salary](https://github.com/doocs/leetcode/tree/master/solution/177.Nth%20Highest%20Salary) | `SQL` |
91+
| 178 | [Rank Scores](https://github.com/doocs/leetcode/tree/master/solution/178.Rank%20Scores) | `SQL` |
9192
| 328 | [Odd Even Linked List](https://github.com/doocs/leetcode/tree/master/solution/328.Odd%20Even%20Linked%20List) | `Linked List` |
9293

9394

solution/178.Rank Scores/README.md

+116
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
## 分数排名
2+
### 题目描述
3+
4+
编写一个 SQL 查询来实现分数排名。如果两个分数相同,则两个分数排名(Rank)相同。请注意,平分后的下一个名次应该是下一个连续的整数值。换句话说,名次之间不应该有“间隔”。
5+
```
6+
+----+-------+
7+
| Id | Score |
8+
+----+-------+
9+
| 1 | 3.50 |
10+
| 2 | 3.65 |
11+
| 3 | 4.00 |
12+
| 4 | 3.85 |
13+
| 5 | 4.00 |
14+
| 6 | 3.65 |
15+
+----+-------+
16+
```
17+
18+
例如,根据上述给定的 `Scores` 表,你的查询应该返回(按分数从高到低排列):
19+
```
20+
+-------+------+
21+
| Score | Rank |
22+
+-------+------+
23+
| 4.00 | 1 |
24+
| 4.00 | 1 |
25+
| 3.85 | 2 |
26+
| 3.65 | 3 |
27+
| 3.65 | 3 |
28+
| 3.50 | 4 |
29+
+-------+------+
30+
```
31+
32+
### 解法
33+
对于每一个分数,找出表中有多少个 `>=` 该分数的不同的(distinct)分数,然后按降序排列。
34+
35+
```sql
36+
# Write your MySQL query statement below
37+
38+
select Score, (select count(distinct Score) from Scores where Score >= s.Score) Rank from Scores s order by Score desc;
39+
40+
```
41+
42+
#### Input
43+
```json
44+
{
45+
"headers": {
46+
"Scores": [
47+
"Id",
48+
"Score"
49+
]
50+
},
51+
"rows": {
52+
"Scores": [
53+
[
54+
1,
55+
3.50
56+
],
57+
[
58+
2,
59+
3.65
60+
],
61+
[
62+
3,
63+
4.00
64+
],
65+
[
66+
4,
67+
3.85
68+
],
69+
[
70+
5,
71+
4.00
72+
],
73+
[
74+
6,
75+
3.65
76+
]
77+
]
78+
}
79+
}
80+
```
81+
82+
#### Output
83+
```json
84+
{
85+
"headers": [
86+
"Score",
87+
"Rank"
88+
],
89+
"values": [
90+
[
91+
4.0,
92+
1
93+
],
94+
[
95+
4.0,
96+
1
97+
],
98+
[
99+
3.85,
100+
2
101+
],
102+
[
103+
3.65,
104+
3
105+
],
106+
[
107+
3.65,
108+
3
109+
],
110+
[
111+
3.5,
112+
4
113+
]
114+
]
115+
}
116+
```

0 commit comments

Comments
 (0)