How to use aggregate functions with GROUP BY in MySQL?
Uses COUNT(), SUM(), AVG(), MIN(), MAX() with GROUP BY and HAVING clauses.
-- Aggregate salary metrics across all employees
SELECT
COUNT(*) AS total_employees,
AVG(salary) AS average_salary,
MIN(salary) AS lowest_salary,
MAX(salary) AS highest_salary,
SUM(salary) AS total_payroll
FROM employees;
-- Group by hiring year with HAVING threshold
SELECT
YEAR(hire_date) AS join_year,
COUNT(*) AS hires_count
FROM employees
GROUP BY YEAR(hire_date)
HAVING hires_count >= 1;+-----------------+----------------+---------------+----------------+---------------+ | total_employees | average_salary | lowest_salary | highest_salary | total_payroll | +-----------------+----------------+---------------+----------------+---------------+ | 3 | 65833.333333 | 60500.00 | 75000.00 | 197500.00 | +-----------------+----------------+---------------+----------------+---------------+