Subqueries and CTEs · Problem 69 of 118

Department Share of Courses

MediumSubqueries and CTEsSchool data

Return the department name as department, courses (how many courses it has) and percent (its share of all courses, rounded to 1 decimal). Include only departments that have courses. Sort by courses from high to low, then department.

Hint 1

The total number of courses does not depend on the group, so a scalar subquery (SELECT COUNT(*) FROM courses) gives it.

Reference solution

SELECT d.name AS department,
       COUNT(*) AS courses,
       ROUND(100.0 * COUNT(*) / (SELECT COUNT(*) FROM courses), 1) AS percent
FROM courses AS c
JOIN departments AS d ON d.department_id = c.department_id
GROUP BY d.department_id, d.name
ORDER BY courses DESC, department;

Inside a grouped query, COUNT(*) is the count of the group. To compare a group with the whole, you need the overall number from somewhere else: a scalar subquery here, or a window function (SUM(COUNT(*)) OVER ()) in the next chapter. Note the 100.0 *: with integers the division would give 0 for every share below 100%.