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 · key | plantext | regiontext | signed_up_attext |
|---|---|---|---|
| 1 | pro | US | 2025-01-01 |
| 2 | free | US | 2025-01-02 |
| 3 | team | EU | 2025-01-02 |
| 4 | pro | IN | 2025-01-03 |
| 5 | free | EU | 2025-01-04 |
showing 5 of 6 rows
ai_requests7 columns · 12 rows
| idinteger · key | account_idinteger | modeltext | requested_attext | input_tokensinteger | output_tokensinteger | statustext |
|---|---|---|---|---|---|---|
| 1 | 1 | swift | 2025-01-01 10:00:00 | 1000 | 200 | success |
| 2 | 1 | reason | 2025-01-02 11:00:00 | 2000 | 600 | success |
| 3 | 2 | swift | 2025-01-02 12:00:00 | 500 | 0 | error |
| 4 | 3 | reason | 2025-01-02 13:00:00 | 8000 | 2000 | success |
| 5 | 3 | swift | 2025-01-03 14:00:00 | 4000 | 1000 | success |
showing 5 of 12 rows
invoices4 columns · 6 rows
| idinteger · key | account_idinteger | periodtext | billed_amountreal |
|---|---|---|---|
| 1 | 1 | 2025-01 | 20 |
| 2 | 3 | 2025-01 | 80 |
| 3 | 4 | 2025-01 | 20 |
| 4 | 6 | 2025-01 | 80 |
| 5 | 1 | 2025-02 | 20 |
showing 5 of 6 rows