Highest Grade For Each Student LeetCode Solution

Last updated on October 9th, 2024 at 09:58 pm

This Leetcode problem Highest Grade For Each Student LeetCode Solution is done in SQL.

List of all LeetCode Solution

Level of Question

Medium

Highest Grade For Each Student LeetCode Solution

Highest Grade For Each Student LeetCode Solution

Problem Statement

Column NameType
student_idint
course_idint
gradeint
Table: Enrollments

(student_id, course_id) is the primary key of this table.

Write a SQL query 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. The output must be sorted by increasing student_id.

Example 1:
Input:

student_idcourse_idgrade
2295
2395
1190
1299
3180
3275
3382
Enrollments table:

Output:

student_idcourse_idgrade
1299
2295
3382

1. Highest Grade For Each Student LeetCode Solution MySQL

select 
  student_id, 
  min(course_id) as course_id, 
  grade 
from 
  Enrollments 
where 
  (student_id, grade) in (
    select 
      student_id, 
      max(grade) 
    from 
      Enrollments 
    group by 
      student_id
  ) 
group by 
  student_id 
order by 
  student_id asc;
Scroll to Top