Chapter 610m
SQL GROUP BY
Aggregate data with GROUP BY, HAVING, COUNT, SUM, AVG.
This content is not yet available in or. Showing English version.
View in English →SQL GROUP BY
GROUP BY groups rows that have the same values.
COUNT
sql
SELECT department, COUNT(*) as employee_count
FROM employees
GROUP BY department;SUM and AVG
sql
SELECT department, SUM(salary) as total, AVG(salary) as average
FROM employees
GROUP BY department;HAVING (filter after grouping)
sql
SELECT department, COUNT(*) as count
FROM employees
GROUP BY department
HAVING COUNT(*) > 5;Multiple Columns
sql
SELECT department, job_title, COUNT(*) as count
FROM employees
GROUP BY department, job_title;Example
sql-- Count employees per department
SELECT department, COUNT(*) as count, AVG(salary) as avg_salary
FROM employees
GROUP BY department
ORDER BY count DESC;