Aggregating and joining: GROUP BY and JOIN
So far we have selected and filtered individual rows. But finance questions are usually about totals: total revenue by region, average sale by product. This is aggregation, and it is where SQL becomes powerful.
Aggregate functions and GROUP BY
SQL has built-in functions that summarise many rows into one number: SUM (total), COUNT (how many), AVG (average), MIN, MAX. Used alone, they collapse the whole table to one number:
SELECT SUM(amount)\nFROM sales;This returns the grand total of all sales. But usually you want a total per category, for example per region. That is what GROUP BY does: it splits the rows into groups and applies the aggregate to each group:
SELECT region, SUM(amount)\nFROM sales\nGROUP BY region;Read it as: "for each region, give me the total amount." The database gathers all the US rows and sums them, all the UK rows and sums them, and returns one row per region:
| region | SUM(amount) |
|---|---|
| US | 400 |
| UK | 50 |
That single query just answered "what is our revenue by region?" on data of any size. This GROUP BY pattern is the workhorse of financial reporting.
What is a JOIN?
Real databases split data across multiple tables to avoid repetition. The sales table might store a customer_id, while the customer's name and country live in a separate customers table. To answer "total sales by customer country," you need data from both tables. A JOIN combines tables by matching a shared column, called a key (here, customer_id):
SELECT customers.country, SUM(sales.amount)\nFROM sales\nJOIN customers ON sales.customer_id = customers.id\nGROUP BY customers.country;The new line, JOIN customers ON sales.customer_id = customers.id, tells the database: "for each sale, find the matching customer by lining up customer_id with the customer's id, and bring their columns alongside." Now you can group by the customer's country even though that information lived in a different table. JOINs are how you connect customers, sales, products and regions into one answer, and mastering them unlocks most real business questions.
- Aggregate functions: SUM, COUNT, AVG, MIN, MAX summarise many rows.
- GROUP BY produces one aggregated row per category (e.g. per region).
- A JOIN combines tables by matching a shared key.
- SELECT, WHERE, GROUP BY, JOIN, ORDER BY cover most real work.