Pivot request statuses into columns with conditional aggregation

MediumSQL

Why it matters Status breakdowns per model, per route or per day are the core of every LLM reliability dashboard.

An LLM gateway dashboard shows, for each model, how many requests succeeded, errored or timed out, plus a failure rate. One query with CASE inside the aggregates builds the whole table.

Write query() returning a SQLite SQL string. Table requests(id INTEGER, model TEXT, status TEXT) where status is 'ok', 'error' or 'timeout'.

Return one row per model: (model, n_ok, n_error, n_timeout, fail_pct) where fail_pct = ROUND(100.0 * (n_error + n_timeout) / total, 1) and total is the model's number of rows. Order by model ascending.

Signaturedef query()

Example

model 'a' with ok, ok, error, timeout gives [('a', 2, 1, 1, 50.0)].

Understand the idea

Conditional aggregation puts a CASE expression inside an aggregate, so one GROUP BY can count several categories side by side. It turns a long table into a wide summary in a single pass.

Worked example for model a with statuses ok, ok, error, timeout: CASE WHEN status = 'ok' THEN 1 ELSE 0 END gives 1, 1, 0, 0, which sums to 2. The same for error gives 1 and for timeout gives 1. Failures = 2 of 4, so fail_pct = 100.0 * 2 / 4 = 50.0.

Rule: n_x = SUM(CASE WHEN condition THEN 1 ELSE 0 END). A rate is 100.0 * n_x / COUNT(*).

Reliability dashboards for LLM APIs, eval pass and fail tables, and A/B test summaries are all built this way.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: example_run1(query())
  • Sample 2: rates that are not whole numbers_run2(query())
  • Test 3: one failure in six_run3(query())