SELECT - GROUP BY
groups rows by key columns and computes aggregates
What changes
- Input
- rows after WHERE
- Output or change
- one row per group
Syntax at a glance
GROUP BY { column-expression | ROLLUP ( <group_by_expression> [ , ...n ] ) | CUBE ( <group_by_expression> [ , ...n ] ) | GROUPING SETS ( <grouping_set> [ , ...n ] ) | () --calculates the grand total } [ , ...n ]
Work example
A report needs one total for each region rather than one result per sale.
Run the sample and check that each output group has one row. Add every non-aggregated selected column to GROUP BY.
Check your work SELECT - GROUP BY. North totals 25 and South totals 8. No sale-level row remains in the grouped result.
Practice SQL
Open in SQL FlowSELECT Region, SUM(Amount) AS Total
FROM (VALUES (N'North', 10), (N'North', 15), (N'South', 8)) AS Sales(Region, Amount)
GROUP BY Region
ORDER BY Region;
Open Microsoft Learn for full syntax, permissions, and details for your version.