Complete worked example
sql
WITH apps AS (SELECT role_id, COUNT(*) AS n FROM applications GROUP BY role_id),
skills AS (SELECT role_id, COUNT(*) AS n FROM role_skills GROUP BY role_id)
SELECT r.id, COALESCE(a.n,0) AS applications, COALESCE(s.n,0) AS skills
FROM roles r LEFT JOIN apps a ON a.role_id=r.id
LEFT JOIN skills s ON s.role_id=r.id ORDER BY r.id;- Reasoning
- Each grouped child has at most one row per role identity.