Intermediate-level SQL GROUP BY practice exercises with solutions.
Exercise 1
Question: Count the number of employees in each department.
SELECT department, COUNT(*) AS employee_count FROM employees GROUP BY department;
GROUP BY groups rows by one or more columns. Aggregate functions like COUNT operate on each group.
Exercise 2
Question: Calculate the average salary by department, ordered highest to lowest.
SELECT department, AVG(salary) AS avg_salary FROM employees GROUP BY department ORDER BY avg_salary DESC;
You can use column aliases in ORDER BY. The query calculates average salary per department.