Aggregation and Grouping · Problem 36 of 118

Attendance Rate

MediumAggregation and GroupingSchool data

For section_id 1 to 6, return section_id, records (attendance rows) and present_percent: the percentage of rows with status = 'present', rounded to 1 decimal. Sort by section_id.

Hint 1

Count the present rows with a conditional sum, then divide by the total and multiply by 100.0.

Reference solution

SELECT section_id,
       COUNT(*) AS records,
       ROUND(100.0 * SUM(CASE WHEN status = 'present' THEN 1 ELSE 0 END) / COUNT(*), 1) AS present_percent
FROM attendance
WHERE section_id BETWEEN 1 AND 6
GROUP BY section_id
ORDER BY section_id;

A percentage is part / total * 100. With integers, part / total is integer division and gives 0 for any part smaller than the total; multiply by 100.0 before dividing (or make one side a decimal). The AVG(condition) shortcut works because the average of 1s and 0s is the share of 1s.

Another way. The average of a 1/0 condition is the share of rows where it is true.

SELECT section_id,
       COUNT(*) AS records,
       ROUND(100.0 * AVG(status = 'present'), 1) AS present_percent
FROM attendance
WHERE section_id BETWEEN 1 AND 6
GROUP BY section_id
ORDER BY section_id;