OpenAI tracks every API request in a table called api_requests:
api_requests (
request_id UUID PRIMARY KEY,
org_id VARCHAR(64),
model VARCHAR(50), -- 'gpt-4o', 'gpt-4o-mini', 'o1', 'o3-mini', etc.
prompt_tokens INT,
completion_tokens INT,
total_tokens INT,
latency_ms INT,
status_code INT, -- 200, 429 (rate limit), 500, etc.
created_at TIMESTAMP
)
model_pricing (
model VARCHAR(50) PRIMARY KEY,
input_price_per_1k DECIMAL(10, 6), -- $/1K input tokens
output_price_per_1k DECIMAL(10, 6), -- $/1K output tokens
effective_from DATE
)
Write a SQL query that computes a daily cost attribution report for the last 30 days:
Output: date, org_id, model, total_requests, successful_requests, total_input_tokens, total_output_tokens, estimated_cost_usd, p50_latency_ms, p99_latency_ms, error_rate_pct
Order by date DESC, estimated_cost_usd DESC.
Use the most recent pricing that was effective on or before the request date.
Expected Output:
| Column | Type |
|---|
| date | TEXT (YYYY-MM-DD) |
| org_id | TEXT |
| model | TEXT |
| total_requests | INTEGER |
| successful_requests | INTEGER |
| total_input_tokens | INTEGER |
| total_output_tokens | INTEGER |
| estimated_cost_usd | REAL (4 decimal places) |
| p50_latency_ms | INTEGER |
| p99_latency_ms | INTEGER |
| error_rate_pct | REAL (percentage 0-100, 2 decimal places) |
Order by date DESC, estimated_cost_usd DESC.
For percentile calculations, use the nearest-rank method. If a group has only 1 request, p50 = p99 = that request's latency.