-
Notifications
You must be signed in to change notification settings - Fork 0
/
1112. Highest Grade For Each Student
57 lines (46 loc) · 1.69 KB
/
1112. Highest Grade For Each Student
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
Table: Enrollments
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| student_id | int |
| course_id | int |
| grade | int |
+---------------+---------+
(student_id, course_id) is the primary key (combination of columns with unique values) of this table.
grade is never NULL.
Write a solution to find the highest grade with its corresponding course for each student. In case of a tie, you should find the course with the smallest course_id.
Return the result table ordered by student_id in ascending order.
The result format is in the following example.
Example 1:
Input:
Enrollments table:
+------------+-------------------+
| student_id | course_id | grade |
+------------+-----------+-------+
| 2 | 2 | 95 |
| 2 | 3 | 95 |
| 1 | 1 | 90 |
| 1 | 2 | 99 |
| 3 | 1 | 80 |
| 3 | 2 | 75 |
| 3 | 3 | 82 |
+------------+-----------+-------+
Output:
+------------+-------------------+
| student_id | course_id | grade |
+------------+-----------+-------+
| 1 | 2 | 99 |
| 2 | 2 | 95 |
| 3 | 3 | 82 |
+------------+-----------+-------+
---------------------
# Write your MySQL query statement below
with cte as (select student_id ,course_id ,grade,dense_rank() over(partition by student_id order by grade DESC) as DT_rank
from Enrollments )
,
cte2 as (select student_id ,course_id ,grade,dense_rank() over(partition by student_id order by course_id ASC) as dt_rank
from cte
where DT_rank = 1)
select student_id ,course_id ,grade
from cte2
where dt_rank=1