Multiple Aggregates & Complex Grouping: Concept
Module: Aggregate Functions & Grouping
Multiple aggregates with complex grouping combines several metrics (COUNT, SUM, AVG, MIN, MAX) across multiple business dimensions in a single efficient query.
**Why Multiple Aggregates:**
Business questions need multiple metrics:
- How many orders? (COUNT)
- Total revenue? (SUM)
- Average order value? (AVG)
- Price range? (MIN, MAX)
SQL computes all in one pass - much faster than separate queries.
**Complex Grouping:**
Group by multiple columns for finer analysis:
- Sales by region AND category
- Employees by department AND job level
- Revenue by plan AND time period
Each unique combination creates one result row.
**Canonical Pattern:**
SELECT
group_col1, group_col2,
COUNT(*) AS total,
SUM(amount) AS total_amount,
AVG(amount) AS avg_amount,
MIN(amount) AS min_amount,
MAX(amount) AS max_amount
FROM table
WHERE condition
GROUP BY group_col1, group_col2
HAVING aggregate_condition
ORDER BY metric DESC;
Foundation of BI and analytics. Used by data analysts, BI developers, and backend engineers building reporting systems and executive dashboards.
Powers every business dashboard - sales by region+category, employee metrics by department+level, revenue by plan+channel. Essential for comprehensive analytical reports.