/W06
实验Lab: Retail analytics in SQL
- Dataset
- UCI Online Retail (541,909 rows, CC BY 4.0)
- Time
- 3 hours
- Chapters
- Ch 8: SQL for Data Science
- Before you start
- slides ch 8 quiz ch 8 notebook (opens in a new tab)
This week you'll be able to
- Write analytical SQL with joins, CTEs, and aggregations in DuckDB.
- Use window functions for running totals, ranks, and period-over-period change.
- Answer a cohort question in SQL and check the answer against pandas.
Goal
Answer real business questions with analytical SQL in DuckDB: aggregations, CTEs, and window functions. Check one answer in pandas.
Data
Every transaction from a UK online gift retailer, December 2010 to December 2011. The download is about 45 MB.
import duckdb
import pandas as pd
retail = pd.read_csv("https://archive.ics.uci.edu/static/public/352/data.csv", dtype={"InvoiceNo": str, "StockCode": str})
retail["InvoiceDate"] = pd.to_datetime(retail["InvoiceDate"], format="%m/%d/%Y %H:%M")
con = duckdb.connect()
con.register("retail", retail) # Procedure 8.1
con.sql("SELECT COUNT(*) AS n FROM retail").df()Use .df() to get results back as a DataFrame. It works in every recent DuckDB version.
Know the data first
- About 25% of rows have no
CustomerID. - Invoices starting with
Care cancellations. Their quantities are negative. - Revenue is
Quantity * UnitPrice.
Decide how each of these affects each question before you write the query.
Tasks
- Revenue by country, top 10, excluding cancellations (Procedure 8.3). Use
HAVINGto keep countries with at least 100 invoices. - Monthly revenue with month-over-month growth as a percentage (Procedure 8.6).
- For each country, the three best-selling products by revenue. Use
RANK()in a window (Procedure 8.5). - A running total of revenue per customer, ordered by invoice date.
- Cohort retention. Build it with CTEs (Procedure 8.4): find each customer's first-purchase month. Then count how many came back in each later month. Show it as a cohort-by-month table.
- Recompute task 1 in pandas. Check the two answers match.
- Run
EXPLAINon the cohort query (Procedure 8.7). Which step is the most expensive?
Deliverable
A notebook with one query per task and its result, and a two-sentence finding for each.
Done when
- Every query runs from the raw download.
- Cancellations and missing customers are handled on purpose, and each choice is written down.
- Task 1 matches between SQL and pandas.
Stretch
Compute recency, frequency, and monetary value (RFM) per customer in one query. You'll use RFM features again in week 11.