Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Performance & internals
Stage 5: Specialization

Project

The customer analytics pack

Start after Part 8

Stage 2

Goal: Deliver the four analyses every commerce team runs — RFM segmentation, cohort retention, category rankings, and a growth trend — as one documented, reproducible SQL file. Time: ~4–5 hours

The brief

Marketing wants to know who the customers are; finance wants to know where the money moves. One file, analytics.sql, four deliverables, every figure pinned to the fixed analysis date 2025-05-01 so the pack reproduces identically forever:

$ psql -d shopdb -f analytics.sql

Build each deliverable yourself before opening the reference analytics.sql — its comments explain every choice.

The four deliverables

1. RFM segmentation. Per customer: Recency (days from last order to 2025-05-01), Frequency (completed orders), Monetary (lifetime spend, cancelled orders excluded) — plus a plain-English segment (champion, recent, loyal, cooling, at risk, no completed orders). Customers with nothing completed must appear: they are the win-back list.

2. Cohort retention. Group customers by first-order month; show each cohort's size and how many were active again 1, 2 and 3 months later.

3. Category rankings. Delivered revenue and units per category, each with its rank and its share of all revenue — one query, windows over the aggregate.

4. Revenue trend. Monthly delivered revenue on a full January–April spine with month-over-month growth and a running total. Empty months must show as zero, and growth must survive them.

Self-check

Straight from a real run against a fresh shopdb:

Check Expected
RFM top spender Meera — 2108.00 over 2 orders, segment champion
RFM win-back list John and Vikram, no completed orders (John's one order was cancelled)
January cohort size 2 → 1 active a month later → 2 two months later
Top category Laptops: 2400.00, rank 1, 59.1% share
Trend extremes February −93.5%, April +1039.3%, running total 4063.00

A number off? Re-seed (psql -d shopdb -f shopdb.sql), re-run — then read your WHERE clauses against the reference.

Stretch goals (optional)

  • Score R, F and M into thirds with NTILE(3) and build the classic three-digit RFM code.
  • Pivot the cohort table to percentages of cohort size.
  • Make deliverable 4 window over a spine that extends to the current month, so the pack stays honest when new data lands.

Search the guide