Given a table Enrollments that contains student enrollments and their grades for different courses, write a SQL query to find the highest grade with its corresponding course for each student.
Key Requirements:
- Find the maximum grade for each student
- Include the corresponding course_id for that grade
- In case of a tie (same highest grade), select the course with the smallest course_id
- Return results ordered by
student_idin ascending order
The table structure is:
student_id(int): Student identifiercourse_id(int): Course identifiergrade(int): Grade received (never NULL)- Primary key:
(student_id, course_id)
Table Schema
| Column Name | Type | Description |
|---|---|---|
student_id
PK
|
int | Student identifier |
course_id
PK
|
int | Course identifier |
grade
|
int | Grade received by student (never NULL) |
Input & Output
| student_id | course_id | grade |
|---|---|---|
| 1 | 10 | 85 |
| 1 | 11 | 85 |
| 1 | 12 | 82 |
| 2 | 20 | 90 |
| 2 | 21 | 88 |
| student_id | course_id | grade |
|---|---|---|
| 1 | 10 | 85 |
| 2 | 20 | 90 |
Student 1 has grades 85, 85, and 82. The highest grade is 85, achieved in both courses 10 and 11. Since there's a tie, we select course 10 (smaller course_id). Student 2's highest grade is 90 in course 20.
| student_id | course_id | grade |
|---|---|---|
| 1 | 100 | 75 |
| 2 | 200 | 95 |
| 3 | 300 | 88 |
| student_id | course_id | grade |
|---|---|---|
| 1 | 100 | 75 |
| 2 | 200 | 95 |
| 3 | 300 | 88 |
Each student is enrolled in only one course, so their highest (and only) grade is returned with the corresponding course_id.
| student_id | course_id | grade |
|---|---|---|
| 1 | 15 | 90 |
| 1 | 10 | 90 |
| 1 | 20 | 90 |
| 2 | 25 | 85 |
| 2 | 30 | 85 |
| student_id | course_id | grade |
|---|---|---|
| 1 | 10 | 90 |
| 2 | 25 | 85 |
Student 1 has three courses with grade 90. Course 10 is selected as it has the smallest course_id. Student 2 has two courses with grade 85, and course 25 is selected (smaller than 30).
Constraints
-
1 ≤ student_id ≤ 10^5 -
1 ≤ course_id ≤ 10^5 -
0 ≤ grade ≤ 100 -
gradeis neverNULL -
(student_id, course_id)is unique (primary key)