milestone 1/4 Ratios, ROUND & NULLIF
Calculate safe ratios and round your results.
AI Platform Economics · Calculate success rates and usage costs, prevent join fan-out, and reconcile split payments with refunds.
approach
A rate is numerator divided by denominator. Use a real number (100.0) to avoid integer division. NULLIF(x,0) turns a zero denominator into NULL; ROUND controls displayed precision. Preserve that NULL instead of calling an undefined rate zero.
worked-example.sql
SELECT account_id, ROUND(100.0 * SUM(CASE WHEN status='success' THEN 1 ELSE 0 END)/NULLIF(COUNT(*),0),2) AS success_pct FROM ai_requests GROUP BY account_id;
data for this milestone
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
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