Interview Puzzles · Problem 102 of 118

Grade Bands per Section

MediumInterview PuzzlesSchool data

For sections 1 to 5, count the graded enrollments (grade is not NULL) in each band: a (90 or more), b (80 up to but below 90), c (70 up to but below 80), d (60 up to but below 70) and f (below 60). Return section_id, a, b, c, d, f. Sort by section_id.

Hint 1

One SUM(CASE WHEN ... THEN 1 ELSE 0 END) per band.

Reference solution

SELECT section_id,
       SUM(CASE WHEN grade >= 90 THEN 1 ELSE 0 END) AS a,
       SUM(CASE WHEN grade >= 80 AND grade < 90 THEN 1 ELSE 0 END) AS b,
       SUM(CASE WHEN grade >= 70 AND grade < 80 THEN 1 ELSE 0 END) AS c,
       SUM(CASE WHEN grade >= 60 AND grade < 70 THEN 1 ELSE 0 END) AS d,
       SUM(CASE WHEN grade < 60 THEN 1 ELSE 0 END) AS f
FROM enrollments
WHERE section_id BETWEEN 1 AND 5 AND grade IS NOT NULL
GROUP BY section_id
ORDER BY section_id;

Each SUM(CASE ...) is its own counter, so the conditions must not overlap: every graded row should fall into exactly one band, and the five columns should add up to the number of graded rows. Adding that check (a quick a + b + c + d + f) to a report is a good habit. In a plain CASE the bands can be written top-down without upper bounds because the first match wins, but separate counters have no such order.