Six business questions with explicit metric definitions, exact money and tests against hand-calculated answers.
面向数据分析/数据科学实习的 SQL 作品:用整数金额、明确退款口径、完整月份的 cohort 留存率与固定截止日 RFM,展示可核对的分析,而不是只列 SQL 语法。
The dataset is independent synthetic data, generated with a fixed seed. Its numbers demonstrate query behavior; they are not customer research or evidence of business impact. Runtime uses Python's standard-library SQLite only.
Python 3.11 or 3.12, SQLite with window functions (the local verified run used SQLite 3.42.0). From this repository:
python -m pip install -r requirements.txt
python -m pytest -q
python examples/run_queries.py --db runs/sales-v2.db --as-of 2025-12-15 --out runs/report.jsonThe runner builds a synthetic database only when that path is missing. Re-running analyzes the existing database read-only. It prints up to eight rows per question and writes every result row to JSON. There are no network calls, credentials or paid services.
To regenerate data deliberately:
python src/build_db.py --db runs/sales-v2.db --seed 7 --replaceWithout --replace, the builder refuses to overwrite an existing file. Explicit replacement is restricted to this repository directory; use a fresh path for a database elsewhere. SQL errors, malformed/legacy databases, invalid dates and inconsistent data produce exit 2, not a partial success. Success is exit 0. Existing reports are not updated after a failed analysis; check the current command's exit status.
erDiagram
customers ||--o{ orders : places
orders ||--|{ order_items : contains
products ||--o{ order_items : identifies
order_items ||--o{ refunds : receives
- All money is stored as integer USD cents, including a line's immutable unit_price_cents at the time of order. Changing a catalog price cannot change historical sales.
- Completed orders contribute booked sales on order_date. Pending and Cancelled contribute neither sales nor purchase activity.
- Refunds are separate dated events linked to an order line. Partial and multiple refunds are supported; their sum cannot exceed that line's sales. Refunds contribute only when their posting date is on or before the cutoff. This is a simple recorded-sales ledger, not a full accounting recognition model.
- Foreign keys are enabled. Input validation checks schema version, integrity, foreign keys, valid dates, status, signup/order sequencing, integer amounts, missing line items and refund consistency.
- Monetary sums remain integers. Percentages use rounded floating-point arithmetic; an overflow fails the query instead of returning an invented currency total.
- Single currency, no FX, tax, discounts, shipping or physical-return tracking. A refund is not assumed to be a physical return.
The schema and six queries contain the definitions; Python validates and executes them.
| Query | Definition and edge cases |
|---|---|
| Q1. Category sales ledger | Completed order-line sales minus separately aggregated refunds posted through the inclusive cutoff. Separate aggregation prevents join multiplication from multiple refund events. Categories without sales appear with zero amounts. |
| Q2. Top product ranks | Net recorded sales per product within category, using RANK(). Ties are preserved, so the top three ranks may contain more than three products. |
| Q3. Monthly movement | A calendar spine includes inactive complete months as zero. Sales belong to the order month; refunds belong to the posting month. LAG() gives the immediately preceding calendar month. Growth is NULL when the previous net amount is zero or negative. |
| Q4. Observed cohort retention | First observed completed-purchase month defines the cohort. A fixed cohort-size denominator, month offset, distinct active customers and retention percentage are returned for each observed complete month. Observed inactive months return zero; unobserved or partial months are omitted. |
| Q5. RFM snapshot | Registered customers as of cutoff; recency is days since the last completed purchase, frequency is distinct completed orders, monetary value is completed sales minus posted refunds. Non-purchasers remain with frequency/money zero and recency/quartile NULL. Quartiles rank purchasers only, using customer ID to break equal-money ties deterministically. |
| Q6. Observed refund incidence | Distinct completed orders in a category with any posted refund / distinct completed orders in that category, plus refund amount / booked sales. Multiple refund events on an order count once. Recent orders have had less time to receive refunds; this is not a final lifetime refund rate. |
An order spanning categories appears in each relevant category's order count. Category amounts add to the global money total; category order counts must not be added to get a global distinct-order count.
Refunds do not retroactively erase completed purchase activity or its frequency. A fully refunded buyer can therefore have frequency greater than zero and monetary value zero. That is the chosen definition, recorded explicitly rather than hidden in a status filter.
--as-of is a fixed inclusive ISO calendar date; no query uses the computer's current date.
With the default 2025-12-15, Q1/Q2/Q5/Q6 include eligible events through December 15. Q3/Q4 stop at November, the last complete month. On 2025-12-31, December becomes eligible for Q3/Q4. Use a month-end cutoff when reconciling monthly totals to the category ledger.
The database declares metadata.observed_through; the seeded dataset uses 2025-12-31. A later cutoff is rejected so unavailable future months cannot become zero retention. Calendar completeness still assumes that the declared coverage is truthful. Unobserved cells in a cohort pivot should remain NULL or blank, not be filled with zero.
Cohorts are first observed purchases within the supplied history, not proof of a customer's first-ever purchase. There is no order-status history or point-in-time warehouse reconstruction: the cutoff filters event dates in the supplied snapshot.
The tests use a tiny independent fixture rather than just asserting that revenue is positive:
| Fixture as of 2025-03-15 | Exact expected answer |
|---|---|
| Category A | Gross 600 cents, refunds 200, net 400; three completed orders |
| Monthly January / February | Net 450 / 250 cents; January's late refunds are posted in February |
| January cohort | Two purchasers; month 0 retention 100%, month 1 retention 50% |
| March while cutoff is March 15 | Omitted from complete-month retention and ledger |
| March after cutoff advances to March 31 | January cohort has observed month 2 retention 0%; later months remain unobserved |
| Alice's RFM | Recency 38 days, two completed orders, net 400 cents |
| No-purchase customer | Frequency 0, monetary 0, recency/quartile NULL |
| Category A refund incidence | Two refunded orders / three completed = 66.67%; multiple refunds do not duplicate the numerator |
Tests also check historical line prices, full and partial refunds, month gaps, zero growth denominators, future-event exclusion, invalid relations and dates, file preservation, read-only reruns, deterministic seeded outputs, unsupported databases and nonzero SQL failure exits. CI runs this suite on Ubuntu with Python 3.11 and 3.12.
Sample summary JSON is generated from the actual query output. It intentionally previews three rows per question and records each full result's row count. Generate the complete report and reproduce its compact summary:
python examples/run_queries.py --db runs/example.db --seed 7 --as-of 2025-12-15 --out runs/example-report.json
python examples/summarize_report.py --input runs/example-report.json --out reports/sample-summary.jsonThe verified seed-7 run contains 300 customers, 40 products, 831 orders, 2,077 line items and 189 refund events. At 2025-12-15, the category ledger totals 44,326,586 cents booked sales - 3,612,271 cents posted refunds = 40,714,315 cents net. These are reproducibility checks on synthetic data; they do not imply a business finding.
The existing six-question structure and examples/run_queries.py entrypoint are retained. Schema v2 makes deliberate metric changes:
- Float catalog unit_price becomes integer catalog and order-time unit_price_cents.
- The old Shipped/Pending/Returned snapshot changes to Completed/Pending/Cancelled plus dated refunds; Pending is excluded from sales.
- Raw cohort active counts become rates with a denominator, month offsets and complete-month observation rules.
- last_order becomes last_order_date plus explicit recency_days, with no-purchase customers retained.
- The runner reads existing databases instead of silently deleting/rebuilding them, and fails on query errors.
Old databases are rejected without being changed. Keep them and generate a new path such as runs/sales-v2.db. For tests use python -m pytest -q; the previous ad-hoc python tests/test_queries.py command is superseded.
This project demonstrates metric design, cohort censoring, JOIN cardinality, window functions, exact currency handling and evidence-backed SQL validation. It complements a migration reconciler, which focuses on input integrity, and an ML service, which focuses on prediction and delivery.
It is not a production warehouse, statistical experiment, performance benchmark or empirical customer analysis. Extend it with a documented real dataset and an actual decision question before claiming business insight. Code and documentation were improved with AI assistance; reproduce and understand the definitions before presenting the work in an interview.