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:
Product | Amount | SaleDate |
---|---|---|
Apples | 100 | 2024-05-01 |
Apples | 50 | 2024-05-02 |
Oranges | 80 | 2024-05-01 |
Oranges | 40 | 2024-05-03 |
Bananas | 60 | 2024-05-02 |
Bananas | 30 | 2024-05-03 |
Pears | 70 | 2024-05-01 |
Pears | 30 | 2024-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 theGROUP BY
.
Next Steps
Next, you’ll learn how to group by multiple columns for more detailed summaries.