Bug-Free and Buggy Submission Counts
Given employees(id, name, department) and code_submissions(submission_id, employee_id, submission_time, has_bug), list every employee's name with the number of bug-free submissions and the number of buggy submissions, ordered by name. Employees with no submissions should appear with two zeros.
Hints
Hint 1
SUM(CASE WHEN has_bug = 0 THEN 1 ELSE 0 END) and its twin for has_bug = 1 count both kinds in one pass.
Hint 2
Start from employees and LEFT JOIN the submissions; group by the employee id as well as the name.
Solution
Show the approach
Approach
SELECT e.name,
COALESCE(SUM(CASE WHEN s.has_bug = 0 THEN 1 ELSE 0 END), 0) AS bug_free_count,
COALESCE(SUM(CASE WHEN s.has_bug = 1 THEN 1 ELSE 0 END), 0) AS buggy_count
FROM employees e
LEFT JOIN code_submissions s ON s.employee_id = e.id
GROUP BY e.id, e.name
ORDER BY e.name;The LEFT JOIN keeps employees with no submissions; their one unmatched row has NULL in has_bug, which neither CASE branch matches, so both sums are zero. Grouping by e.id as well as the name keeps two employees who share a name apart.
Worth saying out loud
- An inner join silently drops the silent employees; it is the first thing to check in anyone's answer.
- A
NULLhas_bugon a real submission falls into neither count; add a thirdCASEfor it orCOUNT(*)as a total to make the gap visible. - Engine shorthands:
COUNT(*) FILTER (WHERE has_bug = 0)on PostgreSQL,COUNTIF(has_bug = 0)on BigQuery,SUM(IF(...))on MySQL. - Restricting to a department or a time range goes in the
ONclause for the submission filter andWHEREfor the employee filter, or theLEFT JOINturns back into an inner one.
Assistant
Sign in to use the assistant — ask what the problem means, get a hint when you're stuck, or have your current work reviewed. Conversations save to your account.