Add lesson 5: GROUP BY and aggregates
3 changed files with 34 additions and 0 deletions
lessons/05-group-by-and-aggregates/README.md ADDED
| @@ -0,0 +1,21 @@ | ||
| 1 | +# Lesson 5: GROUP BY and aggregates | |
| 2 | + | |
| 3 | +GROUP BY and aggregates comes up in almost every real SQL project. We start with the why, then write code together. | |
| 4 | + | |
| 5 | +Full lesson: [https://glibcode.net/courses/sql-essentials/lessons/5](https://glibcode.net/courses/sql-essentials/lessons/5) | |
| 6 | + | |
| 7 | +## Files | |
| 8 | + | |
| 9 | +- `group_by.sql`: aggregates per group and HAVING | |
| 10 | + | |
| 11 | +## Run it | |
| 12 | + | |
| 13 | +```sh | |
| 14 | +sqlite3 shop.db < ../../setup/schema.sql | |
| 15 | +sqlite3 shop.db < ../../setup/seed.sql | |
| 16 | +sqlite3 shop.db < group_by.sql | |
| 17 | +``` | |
| 18 | + | |
| 19 | +## Exercises | |
| 20 | + | |
| 21 | +See [exercises.md](exercises.md). Ask in the forum once you've tried. | |
lessons/05-group-by-and-aggregates/exercises.md ADDED
| @@ -0,0 +1,5 @@ | ||
| 1 | +# Exercises: lesson 5 | |
| 2 | + | |
| 3 | +1. Explain the example to someone who hasn't taken the course. Which part was hardest to explain? | |
| 4 | +2. Rewrite the main part so it runs twice with two different inputs, without copying the code. | |
| 5 | +3. Combine this lesson with the previous one: use something from both in a small program of your own. | |
lessons/05-group-by-and-aggregates/group_by.sql ADDED
| @@ -0,0 +1,8 @@ | ||
| 1 | +-- Revenue per month | |
| 2 | +SELECT strftime('%Y-%m', ordered_at) AS month, | |
| 3 | + COUNT(*) AS orders, | |
| 4 | + SUM(total) AS revenue | |
| 5 | +FROM orders | |
| 6 | +GROUP BY month | |
| 7 | +HAVING revenue > 5000 | |
| 8 | +ORDER BY month; | |