Skip to content

4.2 — GROUP BY: The Game Changer

What You'll Learn

  • How to use GROUP BY to group data in SQL
  • How this compares to grouping rows in Excel PivotTables

Grouping Data in SQL

Here is the sales data we'll use in our examples:

ProductAmountSaleDate
Apples1002024-05-01
Apples502024-05-02
Oranges802024-05-01
Oranges402024-05-03
Bananas602024-05-02
Bananas302024-05-03
Pears702024-05-01
Pears302024-05-03

In Excel, you use PivotTables to group data by a column (like Product). In SQL, you use GROUP BY.

Example: Total sales by product

sql
SELECT Product, SUM(Amount) AS Total_Sales
FROM sales
GROUP BY Product;
  • Each product appears once, with its total sales.

Grouping by SaleDate

Example: Total sales per day

sql
SELECT SaleDate, SUM(Amount) AS Total_Sales
FROM sales
GROUP BY SaleDate
ORDER BY SaleDate;

Key Points

  • GROUP BY lets you summarize data by categories, just like PivotTable row labels.
  • Every column in your SELECT (except aggregates) must be in the GROUP BY.

Next Steps

Next, you’ll learn how to group by multiple columns for more detailed summaries.