topskill.dev
CoursesTracks
0
All courses/Data Analysis Using SQLRefund project 3: reconcile the regional ledger
Joins without inflated totals
9 / 10
← Data Analysis Using SQL
○Define the row before the metric○Exercise: define the row before the metric○Profile missing values without hiding them○Exercise: profile missing values without hiding them○Group records by a business key○Exercise: Group records by a business key○Filter completed groups with HAVING○Exercise: Filter completed groups with HAVING✦Module Quiz
○Remove surrounding spaces with TRIM○Exercise: Remove surrounding spaces with TRIM○Normalize case with LOWER○Exercise: Normalize case with LOWER○Mark a blank as missing with NULLIF○Exercise: Mark a blank as missing with NULLIF○Choose a display fallback with COALESCE○Exercise: Choose a display fallback with COALESCE○Test decimal text with a regular expression○Exercise: Test decimal text with a regular expression○Choose a result value with CASE○Exercise: Choose a result value with CASE○Convert approved text to numeric○Exercise: Convert approved text to numeric✦Module Quiz
○Sum a measure at the chosen grain○Exercise: Sum a measure at the chosen grain○Calculate the mean of known observations○Exercise: Calculate the mean of known observations○Find the smallest known observation○Exercise: Find the smallest known observation○Find the largest known observation○Exercise: Find the largest known observation○Round a numeric report value○Exercise: Round a numeric report value✦Module Quiz
○Count matching rows with FILTER○Exercise: Count matching rows with FILTER○Define both sides of a rate○Exercise: Define both sides of a rate○Compare a row with a computed benchmark○Exercise: compare a row with a computed benchmark○Name analysis steps with CTEs○Exercise: name analysis steps with CTEs○Publish a query definition as a view○Exercise: Publish a query definition as a view○Commit a reporting change as one transaction○Exercise: Commit a reporting change as one transaction○Intake project 1: a reviewable clean layer○Intake project 2: region coverage○Intake project 3: one defensible coverage rate✦Module Quiz
○Make unmatched records visible○Exercise: make unmatched records visible○Prevent join fanout with preaggregation○Exercise: prevent join fanout with preaggregation○Use existence when you do not need child rows○Exercise: use existence when you do not need child rows○Refund project 1: one row per refunded order○Refund project 2: preserve the paid-order population●Refund project 3: reconcile the regional ledger✦Module Quiz
○Interpret an instant in a reporting zone○Exercise: Interpret an instant in a reporting zone○Keep adjacent time periods separate○Exercise: Keep adjacent time periods separate○Bucket calendar months without losing the year○Exercise: bucket calendar months without losing the year○Advance a calendar boundary with INTERVAL○Exercise: Advance a calendar boundary with INTERVAL○Read a date component with EXTRACT○Exercise: Read a date component with EXTRACT○Fill calendar gaps before measuring trends○Exercise: fill calendar gaps before measuring trends✦Module Quiz
○Keep detail rows while computing group shares○Exercise: keep detail rows while computing group shares○Assign a unique position with ROW_NUMBER○Exercise: Assign a unique position with ROW_NUMBER○Share tied positions with RANK○Exercise: Share tied positions with RANK○Number distinct value levels with DENSE_RANK○Exercise: Number distinct value levels with DENSE_RANK○Retain one source version per event○Exercise: Retain one source version per event✦Module Quiz
○Look back one observation with LAG○Exercise: Look back one observation with LAG○Look ahead one observation with LEAD○Exercise: Look ahead one observation with LEAD○Accumulate a running total with an explicit frame○Exercise: Accumulate a running total with an explicit frame○Restrict a total to a trailing row window○Exercise: Restrict a total to a trailing row window○Interpolate a percentile with PERCENTILE_CONT○Exercise: Interpolate a percentile with PERCENTILE_CONT○Choose an observed percentile with PERCENTILE_DISC○Exercise: Choose an observed percentile with PERCENTILE_DISC○Daily briefing 1: a complete daily layer○Daily briefing 2: cumulative and trailing totals○Daily briefing 3: changes with honest baselines○Rank a review queue without erasing ties○Exercise: rank a review queue without erasing ties✦Module Quiz
○Build a cohort from the first eligible purchase○Exercise: build a cohort from the first eligible purchase○Reduce repeated activity to one row per combination○Exercise: Reduce repeated activity to one row per combination○Count distinct known identities○Exercise: Count distinct known identities○Separate zero retention from an unobserved period○Exercise: separate zero retention from an unobserved period○Require the funnel steps to happen in sequence○Exercise: require the funnel steps to happen in sequence○Measure recency at a fixed cutoff○Exercise: Measure recency at a fixed cutoff○Measure purchase frequency at order grain○Exercise: Measure purchase frequency at order grain○State the monetary measure in a member report○Exercise: State the monetary measure in a member report○Apply a segment policy to prepared RFM measures○Exercise: Apply a segment policy to prepared RFM measures✦Module Quiz
○Create an empty reporting table○Exercise: Create an empty reporting table○Protect report row identity with a primary key○Exercise: Protect report row identity with a primary key○Protect a reporting relationship with REFERENCES○Exercise: Protect a reporting relationship with REFERENCES○Load query results with INSERT ... SELECT○Exercise: Load query results with INSERT ... SELECT○Model a report with facts and dimensions○Exercise: model a report with facts and dimensions○Reconcile independent sources and name the limits○Exercise: reconcile independent sources and name the limits○Inspect the proposed query plan○Exercise: Inspect the proposed query plan○Declare an index for a filter column○Exercise: Declare an index for a filter column✦Module Quiz
○Quarter review 1: freeze the report population○Quarter review 2: apply the refund cutoff once○Quarter review 3: regional evidence with an unmatched bucket○Quarter review 4: a monthly trend with a stable definition○Quarter review 5: publish a reconciled evidence table✦Module Quiz
○Define activity churn before counting players○Stage 1: establish the observed play stream○Stage 2: preserve each player and last-seen history○Stage 3: classify inactivity without losing exclusions○Stage 4: compare cohort and channel denominators○Stage 5: reconcile eligibility and boundary cases○Stage 6: prioritize investigation with honest evidence✦Module Quiz

Refund project 3: reconcile the regional ledger

Data model

Exercise data

These objects are loaded at the start. Only the query inputs and their required lineage are listed; other tables in a shared seed are not part of this report.

members

One row represents one registered member.

Field / SQL typeMeaningRules
member_id · integerRegistered-member identifier, distinct from an import receipt or text member_key.Primary key; unique. Required; cannot be NULL.
region · textCurrent member region, not the region at the date of a past purchase.Nullable; NULL means the current region is unrecorded.
joined_on · dateRegistration calendar date, without a time of day or time zone.Required; cannot be NULL.
channel · textRecorded acquisition channel, such as search or referral; not a causal explanation of behavior.Nullable; NULL means acquisition attribution is unknown.

Region and channel labels are not enforced enumerations. This current-member dimension has no region-change history.

orders

One row represents one submitted order.

Field / SQL typeMeaningRules
order_id · integerOrder identifier; equal order totals still belong to separate orders.Primary key; unique. Required; cannot be NULL.
member_id · integerMember key used to look up a registered member; no foreign key is declared.Nullable; NULL means the identifier or reference is unrecorded.
placed_at · timestamp with time zoneOrder occurrence instant, interpreted in UTC unless the query explicitly chooses a local reporting zone.Required; cannot be NULL.
status · textOrder status: paid, pending and cancelled occur in the snapshot; paid defines revenue eligibility.Required; cannot be NULL.
amount · numeric(10,2)Whole-order gross amount in USD before refunds, not a unit price or an order-line amount.Nullable; NULL means the order gross amount is unknown, not zero.
coupon · textOptional coupon code recorded on the order.Nullable; NULL means no coupon code is recorded.

The status labels are observed values, not a CHECK constraint. Paid amounts are known in this supplied snapshot; the nullable column also contains an unknown pending amount. No nonnegative-amount rule or member foreign key is declared. An orphan member key is a real order, not a member registration. The supplied orphan key is 99.

paid_ledger

One row represents one paid order.

Field / SQL typeMeaningRules
order_id · integerOrder identity inherited unchanged from orders.order_id.Non-NULL by query lineage, not a declared NOT NULL constraint. Logical unique non-NULL key inherited from the base primary key; no view primary key is declared.
member_id · integerMember key inherited from the order; it may be missing or unmatched.May be NULL under its source or expression policy.
gross · numeric(10,2)Whole-order gross USD before refunds, inherited from orders.amount.May be NULL under its source or expression policy. The base amount is nullable; known paid sample values do not make the view enforce NOT NULL.
refunded · numericTotal recorded refund USD for this order after any stated cutoff, with absent summaries displayed as zero.Non-NULL by query lineage, not a declared NOT NULL constraint. COALESCE makes the output non-NULL; it does not impose a physical constraint or prove source completeness.
net · numericOrder gross USD minus its aggregated refunded USD.May be NULL under its source or expression policy. A missing gross amount propagates to net; known sample net amounts do not create a NOT NULL constraint.

This ordinary view stores a query definition, not frozen rows; it has no independently declared primary key, foreign key or NOT NULL constraint.

The preaggregated refund side cannot multiply a paid order. Zero for absent refunds relies on the complete supplied snapshot, not a guarantee that unknown refund amounts are zero.

refund_by_order

One row represents one order key with at least one refund event.

Field / SQL typeMeaningRules
order_id · integerRefund-source order key used for grouping.May be NULL under its source or expression policy. Logical unique group key, including at most one NULL group; not a physical primary key.
refunded · numericSum of refund-event amounts in USD for this order key.May be NULL under its source or expression policy. SUM ignores unknown amounts and is NULL if all amounts in a group are unknown. No declared precision or scale.

This ordinary view stores a query definition, not frozen rows; it has no independently declared primary key, foreign key or NOT NULL constraint.

This full-snapshot summary has one row per order key, not one row per refund; orders with no refund events have no summary row.

refunds

One row represents one refund event, not one refunded order.

Field / SQL typeMeaningRules
refund_id · integerRefund-event identifier; an order can have several different refund IDs.Primary key; unique. Required; cannot be NULL.
order_id · integerLogical parent order identifier; not a declared foreign key.Nullable; NULL means the identifier or reference is unrecorded.
refunded_at · timestamp with time zoneRefund occurrence instant, interpreted in UTC for cutoff tests; no separate receipt time is stored.Nullable; NULL means refund occurrence time is unrecorded.
amount · numeric(10,2)USD amount returned by this one refund event, not the original order gross amount.Nullable; NULL means the event refund amount is unknown, not zero.

Supplied refund amounts are known and positive, but the schema permits NULL and does not enforce positivity. Sum events to order grain before attaching them to an order total. No receipt/version history exists to reconstruct late knowledge on a changing source.

Relationship map

Aliases name query roles, not extra tables: o = orders, r = refund_by_order, l = paid_ledger, m = members.

Each refund_by_order row can match zero or one orders rows; each orders row can match zero or one refund_by_order rows. The stated keys and grouped or deduplicated grain determine these match limits; a child matching column can repeat unless its constraints or query grain make that value unique. Column names alone do not guarantee uniqueness. This is a logical query match, not a declared foreign key between these inputs. Missing or unmatched references need not have a parent.

Each members row can match zero or many paid_ledger rows; each paid_ledger row can match zero or one members rows. The stated keys and grouped or deduplicated grain determine these match limits; a child matching column can repeat unless its constraints or query grain make that value unique. Column names alone do not guarantee uniqueness. This is a logical query match, not a declared foreign key between these inputs. Missing or unmatched references need not have a parent.

Each refunds row can match zero or one orders rows; each orders row can match zero or many refunds rows. The stated keys and grouped or deduplicated grain determine these match limits; a child matching column can repeat unless its constraints or query grain make that value unique. Column names alone do not guarantee uniqueness. This is a logical query match, not a declared foreign key between these inputs. Missing or unmatched references need not have a parent.

An inner join omits nonmatches. A left join retains its left population and a full join retains both populations, using NULLs only for the missing side. These outer-join NULLs differ from unknown values stored in a real row. A one-to-many detail match repeats the other side's fields; preaggregate before summing parent-level money. An EXISTS test only asks whether a match exists and does not copy all matching child rows.

Finish the ledger by grouping its net amounts without hiding orders whose member record is missing.

Project continuity

This is stage 3 of the same report. The seed restores every earlier completed view, and the starter includes the previous stage's complete script. Keep that prefix and replace only the final preview query with this stage's work. You do not need a previous Run to make this lesson work.

Prerequisites: Refund projects 1–2; left joins, grouping and display labels.

Region is a member attribute. Keep the order population on the left and put unknown members in an explicit unmatched group. Sum the ledger measures; do not rejoin raw refunds or line items.

Your Task

  1. Return region, orders, gross, refunded, and net by region from paid_ledger, labeling absent member matches unmatched; order by region.

Edit script.sql, Run to inspect the final table, then Submit. The result checks cover column names, row count, and complete rows. They do not prove a particular view definition or transaction was used.

The desk can now trace a regional total back to its orders and refunds. The unmatched bucket is a data follow-up, not a region to silently omit from the grand total.

Hint 1
1 / 1
HINT 1

Count ledger rows after joining the unique members key.

Take the Quiz →
Files
  • ⋄script.sql
Loading editor…
Press Run to execute your code.