You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Aggregation goes far beyond GROUP BY ... HAVING. This lesson covers GROUPING SETS, ROLLUP, CUBE, the FILTER clause, and conditional aggregation — tools that produce sophisticated summaries in a single query.
SELECT
department,
COUNT(*) AS employee_count,
AVG(salary) AS avg_salary,
MAX(salary) AS max_salary
FROM employees
GROUP BY department
ORDER BY avg_salary DESC;
Filter on aggregated values:
-- Departments with more than 10 employees and average salary above 60,000
SELECT
department,
COUNT(*) AS headcount,
AVG(salary)::numeric(10,2) AS avg_salary
FROM employees
GROUP BY department
HAVING COUNT(*) > 10
AND AVG(salary) > 60000;
Common mistake: Using WHERE instead of HAVING for aggregate conditions.
WHERE COUNT(*) > 10is a syntax error.
Compute multiple levels of aggregation in a single query. Each grouping set defines one grouping:
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.