30. SQL for data analysis — Mini-project
The operations director reviews the 12 stores once a year. She wants one table, one row per store, that answers five questions: how much did the store sell this year, how did it grow against last year, where does it rank in its region, how much of its revenue came from online orders it fulfilled, and which month was its best?
Write a script, store_scorecard.py, that builds this scorecard from data/shop.db with one SQL query. The year is a parameter, so the same script produces next year’s scorecard without a code change. The script prints the scorecard, checks its totals against a second tool, and saves it as a CSV file for the director’s spreadsheet.
The project uses every part of module 30: a read-only connection, joins, GROUP BY, conditional aggregation with CASE, chained CTEs, a ranking window function, a ROW_NUMBER pick, named placeholders, pd.read_sql_query and DuckDB on a CSV file.
Dataset
Section titled “Dataset”data/shop.db, tablesorders(20,228 sales lines, 2023-01-01 to 2024-12-31) andstores(12 stores withstore_id,city,region,size_sqmandopened).data/sales.csv, the same sales lines as a CSV file, for the cross-check.
Two facts matter for the design:
- Online orders are fulfilled by a store, so every line has a
store_id, andchannelsaysonlineorstore. - Store S12 (Denver) opened on 2023-06-15. Its 2023 revenue covers only half a year, so its growth rate is not comparable with the others. The scorecard must flag it.
Requirements
Section titled “Requirements”Your script must:
- Open
data/shop.dbread-only (file:data/shop.db?mode=rowithuri=True) and close the connection at the end. - Build the scorecard with one SQL query of at least three CTEs. Use these named placeholders and no other literal dates:
:prev_start,:startand:end(for 2024:2023-01-01,2024-01-01and2025-01-01). - Compute, per store: the revenue of the year, the growth in percent against the previous year (1 decimal), the rank of the store’s revenue in its region (
RANK()), the online share of its revenue in percent (1 decimal), the revenue per m² (1 decimal) and its best month of the year (01…12, withROW_NUMBER()). - Add a
partialcolumn that is 1 for a store that opened after the start of the previous year and 0 otherwise. - Sort by region, then by rank. Print the scorecard with lines of at most 100 characters.
- Cross-check: the sum of the scorecard revenue must equal the year’s revenue that DuckDB computes from
data/sales.csv, to the cent. - Save the scorecard to
output/store_scorecard_2024.csv, without the pandas index. - End with at least three
assertchecks that would catch a wrong join, a wrong filter or a wrong rank.
The expected output for 2024:
store_id region revenue yoy_pct rank online_pct per_sqm best_month partial S07 East 263924.00 29.1 1 43.3 77.6 12 0 S08 East 148352.73 12.1 2 47.9 72.4 12 0 S09 East 132488.36 18.1 3 48.5 75.3 11 0 S01 North 220899.08 19.0 1 43.4 77.5 12 0 S02 North 141643.50 11.6 2 52.3 72.6 12 0 S03 North 115186.83 17.6 3 43.4 81.1 12 0 S04 South 210733.14 14.0 1 49.3 68.0 12 0 S05 South 160171.41 14.3 2 47.3 69.6 12 0 S06 South 111360.45 31.6 3 46.7 66.3 11 0 S10 West 213238.50 13.3 1 43.9 86.0 12 0 S11 West 141176.27 10.6 2 43.0 74.7 12 0 S12 West 91759.97 50.6 3 44.7 68.0 11 1Total revenue 2024: 1,950,934.24 USD (DuckDB check: 1,950,934.24 USD)Saved output/store_scorecard_2024.csvStep plan
Section titled “Step plan”-
Explore first. Open the database read-only and run small queries with the
show()helper from the lesson: the columns ofstores, the revenue per store and year, the online share per store. Keep these queries; they become your CTEs. -
Write the
yearlyCTE. One row per store with three conditional sums: revenue of the year, revenue of the previous year and online revenue of the year. Filter both years inWHEREwith:prev_startand:end, and split them withCASE WHEN order_date >= :start .... -
Write the
monthlyandbest_monthCTEs.monthlyhas one row per store and month of the year.best_monthnumbers the months of each store by revenue withROW_NUMBER()and keeps number 1. A month tie would still give one row. -
Write the final
SELECT. Joinstoresto both CTEs onstore_idwith a left join, so a store without sales would still appear. Compute the growth, the online share and the revenue per m². AddRANK() OVER (PARTITION BY s.region ORDER BY y.revenue DESC)and thepartialflag with a CASE ons.opened. -
Run it from Python. Pass the three dates in a dict to
pd.read_sql_query(sql, con, params=...). Build the dates from oneYEARvariable with f-strings: dates are values, so they go through placeholders. -
Print and check. Print with
to_string(index=False). Compute the year’s revenue with DuckDB ondata/sales.csv(WHERE year(order_date) = $year) and compare. -
Save and assert. Create
output/, save the CSV and add your asserts: 12 rows, one rank 1 per region, the revenue total, and a flag on S12 only.
A skeleton to start from:
# store_scorecard.py: a yearly scorecard of the 12 stores from data/shop.db.import sqlite3from pathlib import Path
import duckdbimport pandas as pd
YEAR = 2024SCORECARD_SQL = """ WITH yearly AS ( -- TODO: revenue, prev_revenue and online_revenue per store ), monthly AS ( -- TODO: revenue per store and month of the year ), best_month AS ( -- TODO: the top month of each store with ROW_NUMBER() ) SELECT -- TODO: the scorecard columns FROM stores AS s -- TODO: left joins and ORDER BY"""
# TODO: params dict built from YEAR# TODO: read-only connection, read_sql_query, close# TODO: print, DuckDB cross-check, save the CSV, assertsRubric
Section titled “Rubric”| Criterion | Points | Full points when |
|---|---|---|
| Runs as a script | 2 | python store_scorecard.py runs with no error and prints the scorecard |
| Correct numbers | 3 | Every value matches the expected output |
| One parameterized query | 3 | One SQL statement with 3+ CTEs; the dates arrive through :prev_start, :start and :end only |
| Conditional aggregation | 2 | The two years and the online revenue come from CASE inside SUM, in one pass |
| Window functions | 2 | RANK() partitioned by region; the best month with ROW_NUMBER() |
| Joins | 2 | Left joins from stores, on primary keys, with no fan-out |
| Safety and hygiene | 2 | Read-only connection, closed at the end; the output goes to output/, never into data/ |
| Cross-check and asserts | 2 | DuckDB total equals the scorecard total; 3+ meaningful asserts |
| Readable SQL | 2 | One clause per line, clear CTE and column names, comments where a choice is not obvious |
| Total | 20 | 16 or more: you are ready for module 31 |
Stretch goals
Section titled “Stretch goals”- Add a column
best_month_revenuewith the revenue of the best month, and a columndec_share: December’s share of the year. Which stores depend most on the holiday season? - Change
YEARto 2023. Why isyoy_pctempty (NaN) for every store? (Hint: there is no 2022 in the data, andSUMover no values is NULL.) Print a clear note instead of an empty column. - Rewrite the query for DuckDB on
data/sales.csv, withQUALIFYinstead of thebest_monthsubquery. Assert that both engines produce the same table. - Add a command-line interface with
argparse(module 08):python store_scorecard.py --year 2024 --region West. The region must go through a placeholder too. - Add a second sheet: the same scorecard per region, built from the store scorecard with one more CTE.
Reference solution
Section titled “Reference solution”Try the project yourself first. Then compare your script with this one. Your names and comments can differ; your output must not.
Reference solution
# store_scorecard.py: a yearly scorecard of the 12 stores from data/shop.db.import sqlite3from pathlib import Path
import duckdbimport pandas as pd
pd.set_option("display.width", 100)
YEAR = 2024SCORECARD_SQL = """ WITH yearly AS ( -- one pass: both years and online revenue SELECT store_id, SUM(CASE WHEN order_date >= :start THEN revenue END) AS revenue, SUM(CASE WHEN order_date < :start THEN revenue END) AS prev_revenue, SUM(CASE WHEN order_date >= :start AND channel = 'online' THEN revenue END) AS online_revenue FROM orders WHERE order_date >= :prev_start AND order_date < :end GROUP BY store_id ), monthly AS ( -- revenue per store and month of the year SELECT store_id, strftime('%m', order_date) AS month, SUM(revenue) AS revenue FROM orders WHERE order_date >= :start AND order_date < :end GROUP BY store_id, month ), best_month AS ( -- exactly one month per store SELECT store_id, month FROM (SELECT store_id, month, ROW_NUMBER() OVER (PARTITION BY store_id ORDER BY revenue DESC) AS pos FROM monthly) WHERE pos = 1 ) SELECT s.store_id, s.region, ROUND(y.revenue, 2) AS revenue, ROUND(100 * (y.revenue - y.prev_revenue) / y.prev_revenue, 1) AS yoy_pct, RANK() OVER (PARTITION BY s.region ORDER BY y.revenue DESC) AS rank, ROUND(100 * y.online_revenue / y.revenue, 1) AS online_pct, ROUND(y.revenue / s.size_sqm, 1) AS per_sqm, b.month AS best_month, CASE WHEN s.opened > :prev_start THEN 1 ELSE 0 END AS partial FROM stores AS s LEFT JOIN yearly AS y ON y.store_id = s.store_id LEFT JOIN best_month AS b ON b.store_id = s.store_id ORDER BY s.region, rank"""
params = { "prev_start": f"{YEAR - 1}-01-01", "start": f"{YEAR}-01-01", "end": f"{YEAR + 1}-01-01",}con = sqlite3.connect("file:data/shop.db?mode=ro", uri=True)card = pd.read_sql_query(SCORECARD_SQL, con, params=params)con.close()print(card.to_string(index=False))
# Cross-check the total with a second engine on a second source.check_sql = """ SELECT ROUND(SUM(revenue), 2) FROM 'data/sales.csv' WHERE year(order_date) = $year"""(duck_total,) = duckdb.sql(check_sql, params={"year": YEAR}).fetchall()[0]total = card["revenue"].sum()print(f"Total revenue {YEAR}: {total:,.2f} USD (DuckDB check: {duck_total:,.2f} USD)")
Path("output").mkdir(exist_ok=True)out_path = Path("output") / f"store_scorecard_{YEAR}.csv"card.to_csv(out_path, index=False)print("Saved", out_path.as_posix())
# Self-checks.assert len(card) == 12, "every store appears once (no fan-out, no lost store)"assert abs(total - duck_total) < 0.005, "scorecard total equals the DuckDB total"assert (card.groupby("region")["rank"].min() == 1).all(), "one leader per region"assert card.loc[card["partial"] == 1, "store_id"].tolist() == ["S12"]assert card["best_month"].isin([f"{m:02d}" for m in range(1, 13)]).all()store_id region revenue yoy_pct rank online_pct per_sqm best_month partial S07 East 263924.00 29.1 1 43.3 77.6 12 0 S08 East 148352.73 12.1 2 47.9 72.4 12 0 S09 East 132488.36 18.1 3 48.5 75.3 11 0 S01 North 220899.08 19.0 1 43.4 77.5 12 0 S02 North 141643.50 11.6 2 52.3 72.6 12 0 S03 North 115186.83 17.6 3 43.4 81.1 12 0 S04 South 210733.14 14.0 1 49.3 68.0 12 0 S05 South 160171.41 14.3 2 47.3 69.6 12 0 S06 South 111360.45 31.6 3 46.7 66.3 11 0 S10 West 213238.50 13.3 1 43.9 86.0 12 0 S11 West 141176.27 10.6 2 43.0 74.7 12 0 S12 West 91759.97 50.6 3 44.7 68.0 11 1Total revenue 2024: 1,950,934.24 USD (DuckDB check: 1,950,934.24 USD)Saved output/store_scorecard_2024.csvHow it works:
yearlyreads the two years in one pass.WHEREkeeps both years; eachCASEinsideSUMpicks the lines of one year (or one channel). A CASE withoutELSEgives NULL for the other lines, andSUMskips NULLs.monthlyandbest_monthfind each store’s top month.ROW_NUMBER()guarantees one row per store even if two months tie, so the join tobest_monthcannot fan out.- The final query starts from
storesand left-joins both CTEs onstore_id, the primary key of every side: 12 rows in, 12 rows out. RANK()runs after the joins and the aggregation, in theSELECTstep, so it ranks the yearly revenue inside each region.ORDER BY s.region, ranksorts by the alias, which exists afterSELECT.- All dates arrive through named placeholders. Changing
YEARis the only edit needed for another year. - The DuckDB check reads a different source (
sales.csv) with a different engine. Agreement to the cent means the filter and the joins lost or duplicated no line.
Reading the scorecard: New York (S07) leads the East and grew 29.1%. Miami (S06) grew fastest of the full-year stores (31.6%) but remains the smallest of the South. Denver’s 50.6% is flagged as partial: it compares a full year with half a year. Seattle (S10) earns the most per m². December is the best month of almost every store; Philadelphia, Miami and Denver peaked in November.