Consolidate E-Commerce Orders into Fact Records
SQL & DataAuto-graded · 14 test casesLast updated
Process and aggregate relational records across multiple entity tables into a single denormalized fact dataset.
You are tasked with building a data pipeline function that denormalizes multiple entity datasets into a unified fact table centered around order line items.
Write a function build_facts that receives seven lists of dictionaries representing tables: customers, orders, order_items, products, payments, shipments, and refunds. The function must produce a list of dictionaries where each record corresponds to a single line item in order_items.
Each returned dictionary must contain exactly the following keys, ordered as specified:
order_item_idorder_idcustomer_idorder_tspaid_tsshipped_tsproduct_idskucategoryqtyunit_priceline_amountrefund_amountcountrystatuspayment_methodcarrier
Field Calculation and Aggregation Rules:
- Base Grain: The output contains one dictionary per element in
order_items, preserving the input sequence oforder_items. - Line Amount: Computed as
qty * unit_price. - Refund Amount: Sum of
refund_amountacross all entries inrefundsbelonging to the specificorder_item_id. If there are no refunds for an item, default to0(or0.0). - Customer & Product Details: Joined via
order_id->orders->customer_id->customersandproduct_id->products. If a lookup reference is missing, populate missing fields withNone. - Payment Attributes:
paid_ts: The maximum (latest)paid_tsamong all payments associated with the item'sorder_id. If no payments exist, set toNone.payment_method: Themethodof the payment with the highestamountfor the item'sorder_id. If there is a tie for the maximumamount, select the lexicographically smallermethod. If no payments exist, set toNone.
- Shipment Attributes:
shipped_ts: The minimum (earliest)shipped_tsamong all shipments for the item'sorder_id. If no shipments exist, set toNone.carrier: The minimum (lexicographically smallest) non-Nonecarrieracross shipments for the item'sorder_id. If no valid carrier exists, set toNone.
Constraints:
order_itemslength $0 \le N \le 10,000$.- ISO 8601 formatted string timestamps or
Nonevalues can be compared directly or using standard datetime parsing. - String fields may be
Noneif entity relationships are missing or unassigned.
Examples
Example 1
Input: build_facts([], [], [{'order_item_id': 1, 'order_id': 10, 'product_id': 100, 'qty': 2, 'unit_price': 3.5}], [{'product_id': 100, 'sku': 'A-1', 'category': 'books'}], [], [], [])
Output: [{'order_item_id': 1, 'order_id': 10, 'customer_id': None, 'order_ts': None, 'paid_ts': None, 'shipped_ts': None, 'product_id': 100, 'sku': 'A-1', 'category': 'books', 'qty': 2, 'unit_price': 3.5, 'line_amount': 7, 'refund_amount': 0, 'country': None, 'status': None, 'payment_method': None, 'carrier': None}]
Example 2
Input: build_facts([{'customer_id': 7, 'signup_date': '2024-01-01T00:00:00', 'country': 'US'}], [{'order_id': 10, 'customer_id': 7, 'order_ts': '2024-02-01T12:00:00', 'status': 'complete'}], [{'order_item_id': 1, 'order_id': 10, 'product_id': 100, 'qty': 2, 'unit_price': 3.5}], [{'product_id': 100, 'sku': 'A-1', 'category': 'books'}], [{'payment_id': 1, 'order_id': 10, 'paid_ts': '2024-02-02T09:00:00', 'method': 'card', 'amount': 7}, {'payment_id': 2, 'order_id': 10, 'paid_ts': '2024-02-03T09:00:00', 'method': 'wallet', 'amount': 7}], [{'shipment_id': 1, 'order_id': 10, 'shipped_ts': '2024-02-04T09:00:00', 'carrier': 'Parcel', 'ship_cost': 2}], [{'refund_id': 1, 'order_item_id': 1, 'refund_ts': '2024-02-05T09:00:00', 'refund_amount': 1.25, 'reason': 'return'}])
Output: [{'order_item_id': 1, 'order_id': 10, 'customer_id': 7, 'order_ts': '2024-02-01T12:00:00', 'paid_ts': '2024-02-03T09:00:00', 'shipped_ts': '2024-02-04T09:00:00', 'product_id': 100, 'sku': 'A-1', 'category': 'books', 'qty': 2, 'unit_price': 3.5, 'line_amount': 7, 'refund_amount': 1.25, 'country': 'US', 'status': 'complete', 'payment_method': 'card', 'carrier': 'Parcel'}]
Hints
Hint 1
Index static entity datasets (customers, orders, products) using hash maps keying on their primary IDs for O(1) lookups.
Hint 2
Group payments and shipments by order_id prior to iterating over items so that aggregations do not re-scan the arrays.
Hint 3
For payment_method ties, use a custom sort key tuple (-amount, method) to easily determine the winning record.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The target table is indexed by line items from order_items. To prevent performance bottlenecks caused by repeatedly searching child tables for each line item, we pre-process the reference tables into hash maps and group auxiliary records (payments, shipments, refunds) by their key identifier (order_id or order_item_id).
-
Preprocessing / Indexing:
- Construct lookups maps
customer_by_id,order_by_id, andproduct_by_id. - Build grouped lists for
paymentsandshipmentskeyed byorder_id. - Pre-calculate total refund amounts per item in a dictionary keyed by
order_item_id.
- Construct lookups maps
-
Item-by-Item Consolidation:
- For each record in
order_items:- Lookup associated
order,customer, andproductentities using the pre-built lookup maps. - Retrieve associated order payments and calculate:
paid_ts: Find maximum non-nullpaid_tstimestamp.payment_method: Find payment record prioritizing highestamount, breaking ties with lexicographically smallermethod.
- Retrieve associated order shipments and calculate:
shipped_ts: Find minimum non-nullshipped_tstimestamp.carrier: Find lexicographically minimum non-nullcarrier.
- Compute line item amount (
qty * unit_price) and extract aggregated refund total.
- Lookup associated
- For each record in
-
Output Formatting:
- Format each record according to the required list of column keys in exact order.
Complexity
- Time Complexity: $O(N + M)$ where $N$ is the number of
order_itemsand $M$ is the combined number of entries across all input tables. Grouping and index lookups run in linear time. - Space Complexity: $O(N + M)$ to maintain hash tables and store the output list of fact records.
from collections import defaultdict
from datetime import datetime
from typing import Dict, List
COLUMNS = [
"order_item_id", "order_id", "customer_id", "order_ts", "paid_ts",
"shipped_ts", "product_id", "sku", "category", "qty", "unit_price",
"line_amount", "refund_amount", "country", "status", "payment_method",
"carrier"
]
def _timestamp_key(value):
if value is None:
return None
return datetime.fromisoformat(value.replace("Z", "+00:00")) if isinstance(value, str) else value
def build_facts(
customers: List[Dict],
orders: List[Dict],
order_items: List[Dict],
products: List[Dict],
payments: List[Dict],
shipments: List[Dict],
refunds: List[Dict]
) -> List[Dict]:
customer_by_id = {c["customer_id"]: c for c in customers}
order_by_id = {o["order_id"]: o for o in orders}
product_by_id = {p["product_id"]: p for p in products}
paid_by_order = defaultdict(list)
for p in payments:
paid_by_order[p["order_id"]].append(p)
shipped_by_order = defaultdict(list)
for s in shipments:
shipped_by_order[s["order_id"]].append(s)
refund_by_item = defaultdict(float)
for r in refunds:
refund_by_item[r["order_item_id"]] += r["refund_amount"]
result = []
for item in order_items:
order = order_by_id.get(item["order_id"], {})
customer = customer_by_id.get(order.get("customer_id"), {})
product = product_by_id.get(item["product_id"], {})
order_payments = paid_by_order[item["order_id"]]
order_shipments = shipped_by_order[item["order_id"]]
latest_paid = max(
(p["paid_ts"] for p in order_payments if p.get("paid_ts") is not None),
key=_timestamp_key,
default=None,
)
best_payment = min(
order_payments,
key=lambda p: (-p["amount"], p["method"]),
default=None,
)
earliest_shipped = min(
(s["shipped_ts"] for s in order_shipments if s.get("shipped_ts") is not None),
key=_timestamp_key,
default=None,
)
carrier = min(
(s["carrier"] for s in order_shipments if s.get("carrier") is not None),
default=None,
)
row = {
"order_item_id": item["order_item_id"],
"order_id": item["order_id"],
"customer_id": order.get("customer_id"),
"order_ts": order.get("order_ts"),
"paid_ts": latest_paid,
"shipped_ts": earliest_shipped,
"product_id": item["product_id"],
"sku": product.get("sku"),
"category": product.get("category"),
"qty": item["qty"],
"unit_price": item["unit_price"],
"line_amount": item["qty"] * item["unit_price"],
"refund_amount": refund_by_item[item["order_item_id"]],
"country": customer.get("country"),
"status": order.get("status"),
"payment_method": best_payment.get("method") if best_payment else None,
"carrier": carrier,
}
result.append({col: row[col] for col in COLUMNS})
return result