Add lesson 7: Window functions
3 changed files with 33 additions and 0 deletions
lessons/07-window-functions/README.md ADDED
| @@ -0,0 +1,21 @@ | ||
| 1 | +# Lesson 7: Window functions | |
| 2 | + | |
| 3 | +Window functions 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/7](https://glibcode.net/courses/sql-essentials/lessons/7) | |
| 6 | + | |
| 7 | +## Files | |
| 8 | + | |
| 9 | +- `window.sql`: RANK and running totals with window functions | |
| 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 < window.sql | |
| 17 | +``` | |
| 18 | + | |
| 19 | +## Exercises | |
| 20 | + | |
| 21 | +See [exercises.md](exercises.md). Ask in the forum once you've tried. | |
lessons/07-window-functions/exercises.md ADDED
| @@ -0,0 +1,5 @@ | ||
| 1 | +# Exercises: lesson 7 | |
| 2 | + | |
| 3 | +1. Make the example ask for its input instead of using a fixed value. | |
| 4 | +2. Run `window.sql` and change one value. Write down what you expect, then run it again and compare. | |
| 5 | +3. Rewrite the main part so it runs twice with two different inputs, without copying the code. | |
lessons/07-window-functions/window.sql ADDED
| @@ -0,0 +1,7 @@ | ||
| 1 | +SELECT name, department, salary, | |
| 2 | + RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS rank | |
| 3 | +FROM employees; | |
| 4 | + | |
| 5 | +SELECT ordered_at, total, | |
| 6 | + SUM(total) OVER (ORDER BY ordered_at) AS running_total | |
| 7 | +FROM orders; | |