Skip to content

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.

  • data/shop.db, tables orders (20,228 sales lines, 2023-01-01 to 2024-12-31) and stores (12 stores with store_id, city, region, size_sqm and opened).
  • 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, and channel says online or store.
  • 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.

Your script must:

  1. Open data/shop.db read-only (file:data/shop.db?mode=ro with uri=True) and close the connection at the end.
  2. Build the scorecard with one SQL query of at least three CTEs. Use these named placeholders and no other literal dates: :prev_start, :start and :end (for 2024: 2023-01-01, 2024-01-01 and 2025-01-01).
  3. 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, with ROW_NUMBER()).
  4. Add a partial column that is 1 for a store that opened after the start of the previous year and 0 otherwise.
  5. Sort by region, then by rank. Print the scorecard with lines of at most 100 characters.
  6. Cross-check: the sum of the scorecard revenue must equal the year’s revenue that DuckDB computes from data/sales.csv, to the cent.
  7. Save the scorecard to output/store_scorecard_2024.csv, without the pandas index.
  8. End with at least three assert checks that would catch a wrong join, a wrong filter or a wrong rank.

The expected output for 2024:

Expected output
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 1
Total revenue 2024: 1,950,934.24 USD (DuckDB check: 1,950,934.24 USD)
Saved output/store_scorecard_2024.csv
  1. Explore first. Open the database read-only and run small queries with the show() helper from the lesson: the columns of stores, the revenue per store and year, the online share per store. Keep these queries; they become your CTEs.

  2. Write the yearly CTE. 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 in WHERE with :prev_start and :end, and split them with CASE WHEN order_date >= :start ....

  3. Write the monthly and best_month CTEs. monthly has one row per store and month of the year. best_month numbers the months of each store by revenue with ROW_NUMBER() and keeps number 1. A month tie would still give one row.

  4. Write the final SELECT. Join stores to both CTEs on store_id with a left join, so a store without sales would still appear. Compute the growth, the online share and the revenue per m². Add RANK() OVER (PARTITION BY s.region ORDER BY y.revenue DESC) and the partial flag with a CASE on s.opened.

  5. Run it from Python. Pass the three dates in a dict to pd.read_sql_query(sql, con, params=...). Build the dates from one YEAR variable with f-strings: dates are values, so they go through placeholders.

  6. Print and check. Print with to_string(index=False). Compute the year’s revenue with DuckDB on data/sales.csv (WHERE year(order_date) = $year) and compare.

  7. 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 (starter)
# store_scorecard.py: a yearly scorecard of the 12 stores from data/shop.db.
import sqlite3
from pathlib import Path
import duckdb
import pandas as pd
YEAR = 2024
SCORECARD_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, asserts
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
  1. Add a column best_month_revenue with the revenue of the best month, and a column dec_share: December’s share of the year. Which stores depend most on the holiday season?
  2. Change YEAR to 2023. Why is yoy_pct empty (NaN) for every store? (Hint: there is no 2022 in the data, and SUM over no values is NULL.) Print a clear note instead of an empty column.
  3. Rewrite the query for DuckDB on data/sales.csv, with QUALIFY instead of the best_month subquery. Assert that both engines produce the same table.
  4. 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.
  5. Add a second sheet: the same scorecard per region, built from the store scorecard with one more CTE.

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
# store_scorecard.py: a yearly scorecard of the 12 stores from data/shop.db.
import sqlite3
from pathlib import Path
import duckdb
import pandas as pd
pd.set_option("display.width", 100)
YEAR = 2024
SCORECARD_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()
Output
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 1
Total revenue 2024: 1,950,934.24 USD (DuckDB check: 1,950,934.24 USD)
Saved output/store_scorecard_2024.csv

How it works:

  1. yearly reads the two years in one pass. WHERE keeps both years; each CASE inside SUM picks the lines of one year (or one channel). A CASE without ELSE gives NULL for the other lines, and SUM skips NULLs.
  2. monthly and best_month find each store’s top month. ROW_NUMBER() guarantees one row per store even if two months tie, so the join to best_month cannot fan out.
  3. The final query starts from stores and left-joins both CTEs on store_id, the primary key of every side: 12 rows in, 12 rows out.
  4. RANK() runs after the joins and the aggregation, in the SELECT step, so it ranks the yearly revenue inside each region. ORDER BY s.region, rank sorts by the alias, which exists after SELECT.
  5. All dates arrive through named placeholders. Changing YEAR is the only edit needed for another year.
  6. 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.