Show contents
Chapter 6 of 7 · 30 min
Project: a company dashboard
By the end of this chapter, you'll be able to
- Build monthly indicators with CTEs and window functions
- Extract the top N of each group with ROW_NUMBER
- Compute a cohort analysis
- Check query plans and avoid silently wrong aggregations
Step 1: the schema and the indicators
Two STRICT tables, and an index on orders(customer_id, month), which serves both the joins with customers and each customer's monthly calculations:
CREATE TABLE customers (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
country TEXT NOT NULL,
signup TEXT NOT NULL
) STRICT;
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL REFERENCES customers(id),
month TEXT NOT NULL,
amount REAL NOT NULL CHECK (amount > 0)
) STRICT;
CREATE INDEX idx_orders_customer_month ON orders(customer_id, month);
| Indicator | Question | Tool |
|---|---|---|
| Monthly summary | How much this month, and what trend? | CTE + SUM … OVER, LAG |
| Best customers | Who are the two best customers in each country? | ROW_NUMBER() OVER (PARTITION BY country …) |
| Cohorts | Are customers who signed up in July still ordering in October? | CTE + COUNT … FILTER |
The cohort table shows how many customers come back each month.
Text description of the animation
- The starting data: one row per order.
- A CTE aggregates by month: that's the GROUP BY step.
- Window functions compare each month with the previous one, without losing the detail.
- Another CTE computes, for each order, the number of months since signup.
- The cohort table shows how many customers come back each month.
Step 2: the queries
The monthly summary. A CTE aggregates by month, then window functions add the running total and the growth:
WITH monthly AS (
SELECT month, COUNT(*) AS orders, COUNT(DISTINCT customer_id) AS customers, SUM(amount) AS revenue
FROM orders
GROUP BY month
)
SELECT month, orders, customers, revenue,
ROUND(revenue / orders, 2) AS average_basket,
SUM(revenue) OVER (ORDER BY month) AS running_revenue,
ROUND(100.0 * (revenue - LAG(revenue) OVER (ORDER BY month)) / LAG(revenue) OVER (ORDER BY month), 1) AS growth_pct
FROM monthly
ORDER BY month;
month | orders | customers | revenue | average_basket | running_revenue | growth_pct
2026-07 | 3 | 3 | 125 | 41.67 | 125 | NULL
2026-08 | 5 | 5 | 180 | 36 | 305 | 44
2026-09 | 5 | 5 | 205 | 41 | 510 | 13.9
2026-10 | 6 | 6 | 240 | 40 | 750 | 17.1
The two best customers in each country. This is the classic "top N per group" problem: number the rows within each partition, then filter in a second CTE.
WITH spending AS (
SELECT c.country, c.name, SUM(o.amount) AS total
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.id
GROUP BY c.id
),
ranked AS (
SELECT country, name, total,
ROW_NUMBER() OVER (PARTITION BY country ORDER BY total DESC, name) AS rank
FROM spending
)
SELECT country, rank, name, total
FROM ranked
WHERE rank <= 2
ORDER BY country, rank;
country | rank | name | total
Chile | 1 | Camila | 125
Ethiopia | 1 | Dawit | 150
Ghana | 1 | Abena | 160
Ghana | 2 | Grace | 105
Türkiye | 1 | Elif | 30
Vietnam | 1 | Bui | 75
Vietnam | 2 | Hoa | 35
SQLite sorts text byte by byte: a country whose name starts with an accented letter (such as "Österreich") would come after every unaccented letter. For a correct alphabetical sort in a given language, the application sorts the result itself (with Intl.Collator in JavaScript, for example) or uses a collation extension.
Cohorts. A cohort groups the customers who signed up in the same month. For each one, we count how many ordered in their signup month (m0), the following month (m1), and so on. The offset in months is computed by converting YYYY-MM into a number of months (year × 12 + month):
WITH activity AS (
SELECT DISTINCT c.id, c.signup,
(CAST(substr(o.month, 1, 4) AS INTEGER) * 12 + CAST(substr(o.month, 6, 2) AS INTEGER))
- (CAST(substr(c.signup, 1, 4) AS INTEGER) * 12 + CAST(substr(c.signup, 6, 2) AS INTEGER)) AS offset
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.id
)
SELECT signup AS cohort,
COUNT(DISTINCT id) FILTER (WHERE offset = 0) AS m0,
COUNT(DISTINCT id) FILTER (WHERE offset = 1) AS m1,
COUNT(DISTINCT id) FILTER (WHERE offset = 2) AS m2,
COUNT(DISTINCT id) FILTER (WHERE offset = 3) AS m3
FROM activity
GROUP BY signup
ORDER BY signup;
cohort | m0 | m1 | m2 | m3
2026-07 | 3 | 2 | 1 | 3
2026-08 | 3 | 2 | 1 | 0
2026-09 | 2 | 2 | 0 | 0
Reading: of the 3 customers who signed up in July, 2 ordered again in August, 1 in September, and all 3 in October. The August cohort has no month 3 yet: the zero means "not observed yet", not "nobody came back". A real dashboard would show an empty cell.
Choices worth noticing:
- One CTE per step: each indicator can be tested separately by replacing the final
SELECT. COUNT(DISTINCT …)in the summary and the cohorts: a customer who orders twice in a month counts once.- The second sort criterion (
total DESC, name) makes the ranking stable when there's a tie. STRICTtables prevent an amount imported as text from silently skewing the totals.
Your turn
Mini-lab: checking the dashboard's plansSQLite
Result
Click “Run”: the SQL engine (about 1 MB) will load in your browser the first time.
A fresh SQLite database is created on every run, in your browser · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Worked exercise
Solved exercise: each country's weight
Add to the dashboard each country's revenue, its share of total revenue as a percentage (one decimal place), and its rank. Do it in a single query, without a CTE.
Hint 1
GROUP BY c.country, SUM(o.amount) is the country's total. A window function can apply to this aggregated result: SUM(SUM(o.amount)) OVER () is the sum of every country's total.Hint 2
OVER () with no partition and no sort: the window holds every row of the result. For the rank: RANK() OVER (ORDER BY SUM(o.amount) DESC).Show the solution and common mistakes
SELECT c.country, SUM(o.amount) AS revenue,
ROUND(100.0 * SUM(o.amount) / SUM(SUM(o.amount)) OVER (), 1) AS share_pct,
RANK() OVER (ORDER BY SUM(o.amount) DESC) AS rank
FROM orders AS o
JOIN customers AS c ON c.id = o.customer_id
GROUP BY c.country
ORDER BY rank;
country | revenue | share_pct | rank
Ghana | 335 | 44.7 | 1
Ethiopia | 150 | 20 | 2
Chile | 125 | 16.7 | 3
Vietnam | 110 | 14.7 | 4
Türkiye | 30 | 4 | 5
Window functions are computed after the GROUP BY: they see one row per country, and can therefore combine every country's totals. Ghana, with three customers, weighs nearly half the revenue: precious information for the founder, and a dependency risk to watch.
Common mistakes:
- Writing
SUM(o.amount) OVER ()instead ofSUM(SUM(o.amount)) OVER (): SQLite accepts it, but adds up a single amount taken at random from each country (205 instead of 750). It's the bare-column trap again. - Forgetting
100.0: with integer amounts in another database, integer division would give 0 for every country but one.
Summary
- 1A dashboard is built step by step: one CTE per aggregation, then window functions to compare.
- 2Top N per group: ROW_NUMBER() OVER (PARTITION BY …) in a CTE, then WHERE rank <= N.
- 3A cohort analysis counts, for each signup month, the customers active in the following months.
- 4A window function can apply to an aggregate: SUM(SUM(x)) OVER ().
- 5SQLite accepts a bare column next to an aggregate: every non-aggregated column must be in the GROUP BY.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.