Back to results for “Window Functions”
SQL Server › Aggregate Functions & GROUP BY

How does the GROUP BY clause work together with aggregate functions?

Beginner

Answer

GROUP BY splits your rows into separate groups based on the values in one or more columns, and then any aggregate function in your query calculates its result separately for each of those groups instead of for the entire table at once, letting you summarize data by category.
SELECT CustomerId, SUM(Amount) AS TotalSpent
FROM Orders
GROUP BY CustomerId;
Real-world example An online store groups orders by customer id to see exactly how much each individual customer has spent in total, rather than just one grand total across all customers combined.

Common follow-ups: What columns are allowed in the SELECT list when using GROUP BY?;Can you group by more than one column at the same time?