Skip to content

About

Cleaning 1M UK retail transactions into a DuckDB star schema, 11 documented SQL KPI queries, RFM and cohort analysis, and an interactive dashboard (Power BI ready)

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

5 Commits

Folders and files

Repository files navigation

UK Online Retailer: Sales Analytics with SQL, a Star Schema and a Dashboard

Turning one million messy transaction lines into a clean data model, documented SQL KPIs and an executive dashboard.

Anthony Adusei-Poku · MSc Data Science, University of East London (2025)

Python DuckDB Plotly Power BI Data: UCI

TL;DR

  • Cleaned 1,067,371 raw transaction lines from a UK online gift wholesaler (Dec 2009 to Dec 2011) into 1,001,920 valid sales lines, with every rule logged. The cleaning removed 34,335 duplicate rows and £352,435 of orders that were keyed in by mistake and reversed (including a single 80,995-unit order).
  • Modelled the data as a star schema in DuckDB (2 fact tables, 4 dimensions) and wrote 11 documented SQL queries for KPIs, trends, Pareto analysis, cohort retention and RFM segmentation.
  • £18.93m net revenue, 39,383 orders, 5,851 identified customers, £490 average order value.
  • The business is seasonal and concentrated: September to November produced 36.2% of 2010 revenue, the top 10% of customers generate 63.3% of revenue, and RFM "Champions" (25.2% of customers) account for 70.6%.
  • Repeat business is the engine: returning customers produced 78.3% of 2011 revenue, while new customers produced 8.0%. Like-for-like (Jan to Nov) revenue grew only 2.3% year on year.
  • Built an interactive HTML dashboard (Plotly) and a Streamlit app with filters, plus a Power BI-ready CSV export with relationships and 19 DAX measures.

1. Business question

An online retailer of giftware, selling mostly to wholesalers, wants a single trusted view of performance: How is revenue trending? Which products, markets and customers matter most? Do new customers come back, and who should the sales team call first?

2. Data

Online Retail II, UCI Machine Learning Repository: every transaction of a UK-based, registered non-store online retailer between 1 Dec 2009 and 9 Dec 2011. Columns: invoice, stock code, description, quantity, invoice date, unit price, customer ID, country.

Licence: CC BY 4.0. Chen, D. (2012). Online Retail II [Dataset]. UCI Machine Learning Repository. https://doi.org/10.24432/C5CG6D. Raw data (45 MB) is not committed. src/download_data.py downloads it.

3. Method

3.1 Cleaning (Python, src/clean.py)

The raw file is messy in realistic ways. Every rule is logged in results/cleaning_log.csv:

Step Rule Rows removed Rows left
0 Raw rows from both Excel sheets 1,067,371
1 Exact duplicate rows (22,844 of them sit in 1 to 9 Dec 2010, where the two sheets overlap) 34,335 1,033,036
2 Bad-debt adjustment invoices (prefix A) 6 1,033,030
3 Non-merchandise codes: postage, bank charges, Amazon fees, manual adjustments, vouchers, tests 5,813 1,027,217
Cancellations (prefix C) moved to a separate returns table 17,914 1,009,303
4 Stock write-offs (quantity <= 0 on a normal invoice) 3,392 1,005,911
5 Unit price <= 0 2,571 1,003,340
6 Orders reversed within 24 hours by an identical cancellation (same customer, product and quantity), worth £352,435 1,420 1,001,920

Other fixes: upper-cased stock codes and descriptions, one description per product (the most frequent), standardised country names (EIRE to Ireland, RSA to South Africa). 22.6% of lines have no customer ID; they are kept as "guest checkout" for revenue but excluded from customer analytics.

3.2 Star schema (DuckDB, sql/00_build_star_schema.sql)

                 dim_date (739)
                      |
dim_product (4,734) - fact_sales (1,001,920) - dim_customer (5,852, incl. guest = -1)
                      |                      \
                 dim_country (43)        fact_returns (16,494)

3.3 SQL analysis (sql/01 to sql/11)

Each file starts with the business question it answers. Techniques: CTEs, window functions (LAG, NTILE, PERCENT_RANK, running sums), FILTER clauses, date arithmetic and cohort self-joins.

Query Question
01_headline_kpis Revenue, orders, customers, AOV, cancellations
02_monthly_trend Monthly revenue with month-on-month and year-on-year growth
03_top_products Product ranking and cumulative (Pareto) share
04_countries Revenue, customers and AOV by market
05_cohort_retention Monthly acquisition cohorts and repeat purchase
06_rfm_segments / 07 Recency, frequency, monetary scoring and segments
08_day_hour When orders are placed
09_customer_concentration Dependence on the largest customers
10_returns_by_product Products losing the most value to cancellations
11_new_vs_returning New vs returning vs guest revenue by month

Query outputs are saved in results/.

4. Key findings (executive summary)

KPI Value
Gross revenue £19,291,427
Cancelled value £364,084 (1.89% of gross)
Net revenue £18,927,343
Orders 39,383
Identified customers 5,851
Average order value £489.84 (278.6 units per order: a wholesale business)
Revenue from guest checkouts 13.34%

1. Growth is flat once seasonality is removed. Comparing the 11 complete months that exist in both years (January to November), revenue rose from £8.54m in 2010 to £8.74m in 2011, +2.3%. September to November alone delivered 36.2% of 2010 revenue; the peak month was November 2011 (£1.44m) and the low was February 2011 (£0.51m). Stock, staffing and cash planning should be built around the autumn peak.

2. Revenue depends on a small group of loyal customers. The top 1% of customers produce 31.3% of identified-customer revenue and the top 10% produce 63.3%. Returning customers generated 78.3% of 2011 revenue, new customers only 8.0% (guest checkouts the rest).

3. RFM segmentation tells sales who to call. "Champions" (25.2% of customers) hold 70.6% of revenue. The most actionable group is "At risk": 349 customers worth £1.06m in lifetime revenue who used to buy often (median 6 orders) but have not ordered for a median of 334 days. A win-back campaign aimed at them is the cheapest growth available.

Segment Customers % customers % revenue Median days since last order
Champions 1,474 25.2% 70.6% 17
Loyal 1,222 20.9% 14.8% 73
At risk (was loyal) 349 6.0% 6.3% 334
Needs attention 1,144 19.6% 5.4% 403
New / promising 436 7.5% 1.0% 26
About to sleep 379 6.5% 1.0% 97
Lost / hibernating 847 14.5% 0.9% 458

4. New customers come back at a steady but low rate. Across 24 monthly cohorts (Jan 2010 to Dec 2011), a size-weighted 20.6% of new customers order again in their second month and 18.1% are active 12 months later. 27.7% of identified customers only ever placed one order.

5. International revenue is small and concentrated. The UK is 85.3% of revenue. Ireland is the largest export market (£614k), but two customers account for £566k of it, so it behaves like two key accounts rather than a market. The Netherlands (£550k, 22 customers, £2,545 average order) is the strongest genuine export market; Germany (107 customers) and France (93) have the broadest customer bases and the clearest room to grow.

6. A long product tail. 1,041 of 4,719 products (22.1%) produce 80% of revenue. The best seller, the Regency three-tier cakestand, brings in £328k (1.7% of revenue) and also loses the most value to cancellations (£14.4k).

7. Customers order during office hours. 78.1% of orders are placed between 10:00 and 15:59, peaking at 12:00 and on Thursdays. Saturday trading is almost non-existent (30 orders in two years). Marketing emails and customer service cover should follow this pattern.

Recommendations

  1. Win back the 349 "At risk" customers (£1.06m lifetime value) with account-manager calls before the autumn peak.
  2. Protect the top 1% of accounts (31.3% of revenue) with key-account management, since losing one is material.
  3. Grow Germany and France, which already have 90 to 110 customers each, and test a dedicated Netherlands offer.
  4. Plan stock and staffing for September to November, which carries over a third of annual revenue.
  5. Capture customer IDs at checkout: 13.3% of revenue is anonymous and cannot be marketed to.

5. Dashboard

  • Static interactive dashboard: dashboard/sales_dashboard.html, one self-contained file (Plotly) with KPI cards, trend by region, AOV, top products, international markets, cohort heatmap and RFM.
  • Streamlit app with filters (region, country, month range): streamlit run dashboard/app.py. Every chart is a live SQL query against the DuckDB warehouse.
  • Power BI: Power BI Desktop is Windows-only, so the star schema is exported to CSV with a step-by-step guide, relationships and 19 DAX measures (time intelligence, new vs returning, ranking). See powerbi/README.md.

6. Limitations

  • Data ends on 9 Dec 2011, so December 2011 is partial and excluded from growth comparisons.
  • The December 2009 cohort includes every customer already active before the data starts, so it is excluded from retention figures.
  • 22.6% of lines have no customer ID; customer metrics describe identified customers only.
  • No cost or margin data, so the analysis is about revenue, not profit.
  • RFM thresholds (quintiles) and segment rules are a common convention, not tuned to this business.

7. How to run

git clone <this-repo> && cd sales-analytics-sql-dashboard
python -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt
./run_all.sh                       # ~2 minutes: download, clean, warehouse, SQL, charts, dashboard
streamlit run dashboard/app.py     # optional interactive app

Repository structure

sales-analytics-sql-dashboard/
├── src/
│   ├── download_data.py      # downloads UCI Online Retail II, converts to Parquet
│   ├── clean.py              # logged cleaning rules
│   ├── build_warehouse.py    # builds DuckDB star schema, runs all SQL, exports Power BI CSVs
│   ├── make_charts.py        # report charts (PNG) + summary_stats.json
│   └── build_dashboard.py    # self-contained Plotly HTML dashboard
├── sql/                      # star schema DDL + 11 documented analysis queries
├── dashboard/                # sales_dashboard.html + Streamlit app.py
├── powerbi/                  # Power BI guide and DAX measures
├── figures/                  # charts (PNG)
├── results/                  # query outputs (CSV), cleaning log, summary stats
├── data/sample/              # 5,000-row sample of fact_sales
├── docs/                     # dashboard screenshot
└── run_all.sh

Skills shown

Data cleaning and validation (pandas) · dimensional modelling (star schema) · SQL (CTEs, window functions, cohorts, RFM) · DuckDB · KPI design · data visualisation (matplotlib, seaborn, Plotly) · dashboarding (Streamlit, Power BI / DAX) · turning analysis into business recommendations.

About

Cleaning 1M UK retail transactions into a DuckDB star schema, 11 documented SQL KPI queries, RFM and cohort analysis, and an interactive dashboard (Power BI ready)

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages