FOUNDATIONS-4: The JOIN Fan-Out Trap (Why Revenue Doubled!)
Track: Analytics Foundations • Difficulty: Beginner • Mastery Points: 150 PTS
Business Problem Scenario
A junior analyst joined gold.fact_orders (one row per order, with shipping_fee) directly to gold.fact_order_items (one row per item inside an order, with item_price). Because Order #100 had 3 items, its $10 shipping fee was added 3 times ($30 instead of $10)! This is the #1 most common SQL bug in analytics.
Engineering Objective
Compute accurate shipping and item totals per customer without fan-out. • Expected Columns: customer_id, total_shipping, total_items_value • Rules: - Pre-aggregate shipping_fee from gold.fact_orders by customer_id. - Pre-aggregate item_price from gold.fact_order_items (joined to orders for customer_id) by customer_id. - Join the two summaries by customer_id and sort by customer_id ASC.
Target Table: gold.fact_orders (order_id, customer_id, shipping_fee), gold.fact_order_items (item_id, order_id, item_price)
Verification & Architecture Insights
Whenever two tables represent different levels of detail (grain), joining them before aggregating multiplies parent-level metrics! Pre-aggregating each grain in a CTE guarantees every dollar is counted exactly once.