LAB 04 · SQL
The query completed.
The revenue number is still wrong.
The daily revenue model completes and publishes a value almost three times larger than the payment ledger.
No input extract doubled its rows, and no individual order carries an obviously incorrect amount.
Follow row cardinality through the joins before correcting the final aggregate.
MODEL EXCERPT
Revenue aggregation
SELECT
date_trunc('day', o.created_at) AS day,
sum(i.quantity * i.unit_price) AS revenue
FROM orders o
JOIN order_items i ON i.order_id = o.id
JOIN order_status_history h ON h.order_id = o.id
WHERE o.created_at >= :run_date
GROUP BY 1
Item rows are intentionally many per order. The question is whether every subsequent join preserves that expected grain.
EVIDENCE TRAIL
Open the signals in order
01ReconciliationWhere does the total diverge?
Payment ledger: $4,812,094
Revenue model: $14,231,770
Orders in window: 71,204
Distinct order IDs: 71,204The order population is right. The amount becomes inflated only inside the reporting model.
02Join cardinalityAfter which join do rows multiply?
orders × order_items: 182,841 rows
… plus order_status_history: 538,220 rows
Distinct order IDs after join: 71,204
Average history rows/order: 2.94The item amount is repeated once for each historical status record attached to the order.
03Table grainWhat does the status table represent?
order_status_history is an event table: it records every transition for an order. It is not one row per order and cannot be joined to revenue at that grain without first selecting one record.
Reference: PostgreSQL documentation on table expressions.
LIKELY ROOT CAUSEA one-to-many status-history join multiplied each order-item amount before the final SUM.
The aggregate is behaving correctly over the rows it receives. The model creates too many rows before it aggregates.
JOIN order_status_history h ON h.order_id = o.idJOIN latest_order_status h ON h.order_id = o.idREVIEW BEFORE APPLYINGOnly make this change if latest_order_status guarantees one row per order. If status is not needed for this metric, remove the join entirely.