AdvancedSubqueries & EXISTS
Find the employee who has the most project hours in each dept
The query
SQL
SELECT e.first_name, e.last_name, d.dept_name, emp_hours.total_hours
FROM employees e
JOIN departments d ON e.dept_id = d.dept_id
JOIN (
SELECT emp_id, SUM(hours) AS total_hours
FROM project_assignments
GROUP BY emp_id
) emp_hours ON e.emp_id = emp_hours.emp_id
WHERE emp_hours.total_hours = (
SELECT MAX(sub.total_hours)
FROM (
SELECT e2.dept_id, SUM(pa2.hours) AS total_hours
FROM employees e2
JOIN project_assignments pa2 ON e2.emp_id = pa2.emp_id
GROUP BY e2.emp_id, e2.dept_id
) sub
WHERE sub.dept_id = e.dept_id
)
ORDER BY d.dept_name;Note
“Correlated subquery to find department maximum, then matching employees. Alternative: window functions.