◢◤ ARKANE_
SYS_TIME UTC+0
Work with me
/W06

实验Lab: Retail analytics in SQL

week 6
Dataset
UCI Online Retail (541,909 rows, CC BY 4.0)
Time
3 hours

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 C are cancellations. Their quantities are negative.
  • Revenue is Quantity * UnitPrice.

Decide how each of these affects each question before you write the query.

Tasks

  1. Revenue by country, top 10, excluding cancellations (Procedure 8.3). Use HAVING to keep countries with at least 100 invoices.
  2. Monthly revenue with month-over-month growth as a percentage (Procedure 8.6).
  3. For each country, the three best-selling products by revenue. Use RANK() in a window (Procedure 8.5).
  4. A running total of revenue per customer, ordered by invoice date.
  5. 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.
  6. Recompute task 1 in pandas. Check the two answers match.
  7. Run EXPLAIN on 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.

online /teaching/semester-1/labs/6 Newcastle, UK v0.1.0 // rss