Student Course Ranking by Semester
UptoSkills Arena wants to rank students in each course they've taken based on their scores within that specific course.
Tables:
students:student_id(PK),student_namecourses:course_id(PK),course_nameenrollments:enrollment_id(PK),student_id(FK),course_id(FK),semester,score(integer from 0 to 100)
Return the student_name, course_name, semester, score, and the student's rank in that course for that semester. The rank should be 1 for the highest score. Ties should receive the same rank, with the next rank being skipped (e.g., 1, 1, 3).
Order the results by semester, then course_name, then score in descending order.
Tables
CREATE TABLE students ( student_id integer PRIMARY KEY, student_name varchar(100) NOT NULL ); CREATE TABLE courses ( course_id integer PRIMARY KEY, course_name varchar(100) NOT NULL ); CREATE TABLE enrollments ( enrollment_id integer PRIMARY KEY, student_id integer NOT NULL, course_id integer NOT NULL, semester varchar(20) NOT NULL, score integer CHECK (score >= 0 AND score <= 100), FOREIGN KEY (student_id) REFERENCES students(student_id), FOREIGN KEY (course_id) REFERENCES courses(course_id) );
Example data
INSERT INTO students (student_id, student_name) VALUES (1, 'Alice'), (2, 'Bob'), (3, 'Charlie'), (4, 'David'); INSERT INTO courses (course_id, course_name) VALUES (101, 'Math'), (102, 'Physics'), (103, 'Chemistry'); INSERT INTO enrollments (enrollment_id, student_id, course_id, semester, score) VALUES (1, 1, 101, 'Fall 2023', 95), (2, 2, 101, 'Fall 2023', 90), (3, 3, 101, 'Fall 2023', 90), (4, 4, 101, 'Fall 2023', 85), (5, 1, 102, 'Fall 2023', 88), (6, 2, 102, 'Fall 2023', 92), (7, 3, 102, 'Fall 2023', 88), (8, 1, 101, 'Spring 2024', 92), (9, 2, 101, 'Spring 2024', 98), (10, 3, 101, 'Spring 2024', 92);
Your query is also checked on hidden datasets with different data.
Hints
Similar problems
- Delivery Performance RankingMedium
- Rank Student Scores in Each SubjectMedium
- Rank Sales by Consecutive DaysMedium
- Rank Students by Cumulative Score in Each CollegeMedium
- CTE: Top Employee Performance RankingMedium
- Sales Performance: Rank by Consecutive UpswingHard
More in: SQL and Databases problems
-- Rank students by course score within each semester
SELECT
s.student_name,
c.course_name,
e.semester,
e.score
Your query runs on the example tables shown with the problem, then on hidden datasets when you submit.
Write standard SQL. MySQL habits work too: IFNULL, IF, YEAR(), DATE_FORMAT, GROUP_CONCAT, `backticks` and LIMIT 5, 10. It runs on PostgreSQL, so integer division keeps whole numbers (5 / 2 = 2): write 5.0 / 2 for 2.5.