+---------------+---------+
|Column Name |Type|+---------------+---------+
| student_id | int || course_id | int || grade | int |+---------------+---------+
(student_id, course_id) is the primarykey (combination of columns withuniquevalues) 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.
We want, for each student, the course with the highest grade. If there are ties, we want the course with the smallest course_id. Window functions let us rank each row within each student by grade and course_id.
SELECT student_id, course_id, grade
FROM (
SELECT*,
ROW_NUMBER() OVER (PARTITION BY student_id ORDERBY grade DESC, course_id ASC) as rn
FROM Enrollments
) t
WHERE rn =1;
1
2
3
4
5
6
7
SELECT student_id, course_id, grade
FROM (
SELECT*,
ROW_NUMBER() OVER (PARTITION BY student_id ORDERBY grade DESC, course_id ASC) as rn
FROM Enrollments
) t
WHERE rn =1;