runtime
AI Platform Economics · milestone 02 / 04

milestone 2/4 Multi-grain joins without fan-out

Combine metrics at different levels without multiplying totals.

AI Platform Economics · Calculate success rates and usage costs, prevent join fan-out, and reconcile split payments with refunds.

approach

Requests and invoices each have many rows per account. Joining raw tables creates requests × invoices and inflates sums. Aggregate each side to one row per account before joining; keep accounts with zero on either side.

worked-example.sql
WITH usage AS(
  SELECT account_id,COUNT(*) AS request_count
  FROM ai_requests
  GROUP BY account_id
), billing AS(
  SELECT account_id,SUM(billed_amount) AS billed_amount
  FROM invoices
  GROUP BY account_id
)
SELECT
  a.id,
  COALESCE(u.request_count,0) AS request_count,
  COALESCE(b.billed_amount,0) AS billed_amount
FROM ai_accounts a
LEFT JOIN usage u ON u.account_id=a.id
LEFT JOIN billing b ON b.account_id=a.id;

data for this milestone

ai_accounts4 columns · 6 rows
idinteger · keyplantextregiontextsigned_up_attext
1proUS2025-01-01
2freeUS2025-01-02
3teamEU2025-01-02
4proIN2025-01-03
5freeEU2025-01-04

showing 5 of 6 rows

ai_requests7 columns · 12 rows
idinteger · keyaccount_idintegermodeltextrequested_attextinput_tokensintegeroutput_tokensintegerstatustext
11swift2025-01-01 10:00:001000200success
21reason2025-01-02 11:00:002000600success
32swift2025-01-02 12:00:005000error
43reason2025-01-02 13:00:0080002000success
53swift2025-01-03 14:00:0040001000success

showing 5 of 12 rows

invoices4 columns · 6 rows
idinteger · keyaccount_idintegerperiodtextbilled_amountreal
112025-0120
232025-0180
342025-0120
462025-0180
512025-0220

showing 5 of 6 rows

challenge 1

Return id, request_count and billed_amount for every account across all dates. Aggregate requests and invoices separately to avoid multiplication; use zeros for missing totals.

Return idrequest_countbilled_amountany row order

challenge-1.sql
 
3 steps left · check both queries and pass the concept checkNext milestone
Multi-grain joins without fan-out — AI Platform Economics · Runtime