Rank Within Each Course
Feedback letters at Fairhaven University tell a student how they did relative to the people sitting the same course, not relative to the university. A 3.5 is a strong result in a harshly marked course and an ordinary one elsewhere, so a single university-wide ordering would tell most students something misleading about themselves.
Every sitting on record gets a place, including one still waiting on a mark — the letter has to say something about it rather than pretend it does not exist — and an unmarked sitting comes last within its course. Two sittings on the same mark share a place and the following one is skipped.
enrollments — one row per sitting: one student taking one course in one term. student_id points at a row in students and course_id at a row in courses. grade is the mark for that sitting, on the same 0-4 scale, and is NULL when no mark has been entered yet. semester is the term the sitting belongs to.
| student_id | course_id | grade | semester |
|---|---|---|---|
| 1 | 1 | 3.7 | Fall2023 |
| 1 | 2 | 3.9 | Spring2024 |
| 2 | 1 | 3.2 | Fall2023 |
| 2 | 3 | 3.5 | Fall2023 |
| 3 | 2 | 4.0 | Spring2024 |
| 3 | 4 | 3.8 | Spring2024 |
| 4 | 3 | 2.9 | Fall2023 |
| 5 | 1 | 3.6 | Fall2023 |
| 5 | 2 | NULL | Spring2024 |
The table already exists in the database — there is nothing to create or load.
Task: Write a query that returns one row per sitting, with student_id, course_id, grade and the sitting's standing inside its own course as course_rank — 1 for the best mark in that course, and the counting restarting at every course. Sittings sharing a mark share a standing and the following place is skipped; a sitting with no mark entered comes last in its course. Return the rows smallest course_id first, best standing first inside a course, and smallest student_id first if two are still level.
Example output
Shape only — these sittings are invented. Note the three things the shape is showing you: the counting restarts at every course, two sittings level on a mark share a standing and leave the next one unused, and an unmarked sitting still appears, with NULL in grade, at the bottom of its course:
| student_id | course_id | grade | course_rank |
|---|---|---|---|
| 12 | 7 | 3.85 | 1 |
| 19 | 7 | 3.4 | 2 |
| 23 | 7 | 3.4 | 2 |
| 31 | 7 | NULL | 4 |
| 19 | 8 | 3.6 | 1 |
| 12 | 8 | 2.95 | 2 |
Sign in to solve this problem
Reading problems is free for everyone — solving them (Run, Submit, and tracking what you've solved) needs an account.
Sign in