Count per group with GROUP BY
Question
For each department_id, show the department id and the number of employees in it.
employeesid, name, salary, department_id, manager_id, hired_on
departmentsid, name, city
Your query
Ctrl+Enter to run
Result
Expected result
| department_id | employees |
|---|---|
| 1 | 4 |
| 2 | 3 |
| 3 | 2 |
| 4 | 3 |
Hint
GROUP BY makes one group per department; COUNT(*) then counts each group.
Show the solution
solution.sql
Run this code
SELECT department_id, COUNT(*) AS employees
FROM employees
GROUP BY department_id;
Why it works
GROUP BY department_id puts the rows into one bucket per department, and every aggregate in SELECT is calculated per bucket. You get one row per department.
Common mistake
Every column in SELECT must be either in GROUP BY or inside an aggregate. Adding name here would make no sense, since a group has many names.