Databases & SQL Master Course — 197. Capstone Analytical Reports
Lesson 197 Capstone Analytical Reports
Prerequisites and objectives
Complete Lesson 196 and review the earlier concepts named in this lesson. You will publish daily and cumulative paid totals, preserve customers without paid orders, and reconcile product contributions. Review grouped queries, calendar scaffolds, window frames, and zero-versus-missing semantics. The reporting window is declared complete for the three fictional dates. The shared capstone is a fictional workshop-supply shop using one currency, USD cents. Every exercise scenario starts from a new copy of its displayed fixture; changes in another lesson are not assumed to persist.
Shared fixture dependency
Run the exact schema and seed from Lesson 193 in a new disposable SQLite database. The displayed setup is sufficient; no companion download is required. Any additional definition is shown below. Each exercise was verified from this baseline independently, not from the previous exercise’s final state.
Build reports from one consistent fact definition
Every report in this lesson uses paid order lines and their historical unit prices. Different grouping dimensions should reconcile to the same accepted grand total when their populations are equivalent. Changing a report title does not justify using current catalog price or silently including open orders.
The day report first aggregates paid lines by order_day and counts distinct order identities. A calendar relation then supplies the three completed dates, including a day with no paid activity. This is an observed zero under the fixture’s completeness contract, not a future period with insufficient observation.
Dates are canonical ISO text in the accepted source contract, so lexical comparison and ordering follow calendar order for this bounded date range. This does not turn arbitrary text into a validated date. Keep the loader’s format and calendar assumptions visible when extending the report.
CREATE VIEW cap_daily197 AS WITH calendar(day) AS (VALUES('2026-10-01'),('2026-10-02'),('2026-10-03')),
facts AS (SELECT o.order_day,COUNT(DISTINCT o.id) AS orders,SUM(l.units*l.unit_cents) AS cents
FROM cap_order o JOIN cap_line l ON l.order_id=o.id WHERE o.status='paid'
AND o.order_day>='2026-10-01' AND o.order_day<'2026-10-04' GROUP BY o.order_day)
SELECT c.day,COALESCE(f.orders,0) AS orders,COALESCE(f.cents,0) AS cents FROM calendar c LEFT JOIN facts f ON f.order_day=c.day;
| Day | Paid orders | Daily cents | Cumulative cents |
|---|---|---|---|
| 2026-10-01 | 1 | 500 | 500 |
| 2026-10-02 | 1 | 330 | 830 |
| 2026-10-03 | 0 | 0 | 830 |
Distinguish grouping from window calculation
The daily view changes the grain from order lines to calendar day. The cumulative query then applies a window over those daily rows without collapsing them further. Each day retains its daily value and gains a cumulative sum.
Specify ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW so the intended cumulative frame is explicit. The calendar has one row per day, avoiding peer ambiguity here. If several rows share an ordering value in another report, decide whether they should accumulate together or use a unique sequence and a row-based frame.
Customer and product reports use different outer populations. Keeping every customer or every product visible requires a left join to preaggregated accepted facts. A filter on a nullable joined table in WHERE can accidentally remove those zero-activity entities. State the population before choosing predicate placement.
Exercise 1
Read the completed daily scaffold.
Worked solution
-- Connection A
SELECT day,orders,cents FROM cap_daily197 ORDER BY day;
The third day is present with zero orders and zero cents because the accepted reporting window is complete and no qualifying paid facts exist there. The count of days is three, while the total count of paid orders is two; those are different grains.
Exercise 2
Add an explicit cumulative window and reconcile its final value.
Worked solution
-- Connection A
SELECT day,cents,SUM(cents) OVER(ORDER BY day ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_cents FROM cap_daily197 ORDER BY day;
SELECT SUM(cents),SUM(orders) FROM cap_daily197;
The running total reaches eight hundred thirty and remains there on the zero-activity day. The independent sum of daily values agrees with the known paid baseline. A cumulative series should not be summed again to obtain total revenue, because that would repeatedly count earlier days.
Exercise 3
Preserve the complete customer population.
Worked solution
-- Connection A
SELECT c.id,COALESCE(SUM(l.units*l.unit_cents),0) AS paid_cents FROM cap_customer c LEFT JOIN cap_order o ON o.customer_id=c.id AND o.status='paid' LEFT JOIN cap_line l ON l.order_id=o.id GROUP BY c.id ORDER BY c.id;
Ada contributes all accepted paid value. Bo’s open order and Cleo’s lack of orders both produce zero paid cents, without removing either customer. If a report needs to distinguish those operational states, add explicitly defined diagnostic columns instead of changing the monetary population silently.
Exercise 4
Calculate product contributions with an explicit denominator.
Worked solution
-- Connection A
WITH f AS (SELECT l.product_id,SUM(l.units) AS units,SUM(l.units*l.unit_cents) AS cents FROM cap_line l JOIN cap_order o ON o.id=l.order_id WHERE o.status='paid' GROUP BY l.product_id), t AS (SELECT SUM(cents) AS total FROM f) SELECT p.id,COALESCE(f.units,0),COALESCE(f.cents,0),ROUND(100.0*COALESCE(f.cents,0)/NULLIF(t.total,0),2) FROM cap_product p LEFT JOIN f ON f.product_id=p.id CROSS JOIN t ORDER BY p.id;
PEN contributes five units and five hundred thirty cents; PAD contributes one unit and three hundred cents. INK’s open-order line is excluded. The percentage denominator is total accepted paid value, and NULLIF protects the undefined all-zero denominator rather than inventing a meaningful percentage.
Keep rounding and denominator policies visible
The product percentages are rounded only for display. In general, rounded category percentages may not sum to exactly one hundred. Do not alter source amounts to force a visual total. If a presentation distributes rounding differences, document that display-only method separately from the underlying measure.
A zero denominator should not be mislabeled as zero share for every category when the share is mathematically undefined. Choose a visible “not applicable” or missing-state presentation under the reporting contract. This baseline has a nonzero denominator, but the query explicitly protects the zero case.
Do not join several raw child streams such as refunds, events, and lines before aggregating. The capstone avoids those extra relations, but earlier case studies demonstrated the fan-out risk. Additional measures should be reduced to compatible grain before they join this report family.
Publish enough context to reproduce the reports
Record accepted status, monetary unit, date window, source cutoff, historical-price policy, dimension population, and report version. Pair charts with compact data tables or accessible descriptions. A line chart of cumulative cents should not be described as daily sales; its increasing shape reflects accumulation by definition.
Test a no-paid-orders fixture, a newly paid order, a catalog price change, a customer with no activity, and multiple orders on one day. Reconcile daily, customer, and product totals to a direct fact-level control before considering performance optimization. The shared STRICT schema requires SQLite 3.37.0 or later.
Pitfalls and summary
Aggregate facts at the intended report grain, apply windows to that result, and preserve the declared dimension population. Use one consistent eligibility and historical-price definition, label percentages and zero states carefully, and reconcile every view of the data to the accepted controls.
Knowledge check
Question 1
Why does October third show zero rather than disappear?
- The source contains a zero-valued paid order that day
- Every future date must be interpreted as observed zero
- A completed calendar scaffold preserves the date with no accepted facts
- SUM creates missing calendar rows automatically
Answer and explanation
C. The explicit calendar and completeness contract establish the zero-activity day.
Question 2
What does the final cumulative value represent?
- The sum of all cumulative values
- Only the last day’s paid amount
- The average value per customer
- The total accepted paid cents through the last displayed day
Answer and explanation
D. A running sum accumulates the daily measure without changing its monetary unit.
Question 3
Why use historical line prices consistently?
- Dimension reports must reconcile to the same accepted fact definition
- Current catalog prices are always lower than charged prices
- Grouping by product makes current and historical prices equivalent
- An ordinary aggregate is permanently materialized by default
Answer and explanation
A. Different price definitions would produce incompatible totals.
Question 4
What does NULLIF protect in the product share query?
- A missing numerator that should become zero
- An undefined percentage when the accepted total is zero
- Rounding that makes displayed shares total one hundred
- A change from global to selected-product share
Answer and explanation
B. A zero denominator is a measurement-state issue, not a meaningful zero share.
Question 5
Which total should equal 830 cents on the baseline?
- The sum of the cumulative series
- All open and paid order values combined
- Each complete grouping of the same paid facts, including day, customer, and product
- Current catalog repricing of every historical unit
Answer and explanation
C. Equivalent accepted populations should reconcile across grouping dimensions.
Execution scope
These scenarios were executed with SQLite 3.53.1 using separate connections to newly created disposable local database files. No existing or external database was used. Each scenario starts from a fresh fixture. Python was an internal verification harness, not a learner prerequisite. Follow the labeled connection order in SQL clients that open the same disposable file.
Primary references
- Window frames: Explicit cumulative ROWS calculations.
- Grouping and joins: Calendar and dimension populations.
- Aggregates: Counts and monetary controls.
- NULLIF and COALESCE: Undefined denominators and known absence.