Window Functions · Problem 75 of 118

Grade Quartiles

MediumWindow FunctionsSchool data

For section 1, take the enrollments that have a grade and return student_id, grade and quartile, where quartile is 1 for the highest quarter of the grades and 4 for the lowest (four groups of nearly equal size). Sort by grade from high to low, then student_id.

Hint 1

NTILE(4) OVER (ORDER BY grade DESC, student_id).

Reference solution

SELECT student_id,
       grade,
       NTILE(4) OVER (ORDER BY grade DESC, student_id) AS quartile
FROM enrollments
WHERE section_id = 1 AND grade IS NOT NULL
ORDER BY grade DESC, student_id;

NTILE(n) splits the ordered rows into n groups of (almost) equal size and returns the group number. If the rows do not divide evenly, the first groups get one extra row. Remember that equal sizes are not equal value ranges: it is a ranking by position, which is useful for "top 25%" labels, deciles of customers by spending, and so on.