Find models slower than the overall average latency using CTEs
Why it matters Comparisons against a global baseline are common in monitoring, and the weighted vs unweighted average mistake is very common.
A latency report flags models whose average is above the average of ALL calls. The average of all calls is not the same as the average of the per-model averages when models get different traffic.
Write query() returning a SQLite SQL string. Table calls(id INTEGER, model TEXT, latency_ms REAL).
Return (model, avg_ms) for every model whose average latency is strictly greater than the average latency over all rows of calls. avg_ms is ROUND(AVG(latency_ms), 1). Order by avg_ms descending, then model ascending.
def query()Example
model 'a' with 100 and 100, model 'b' with 400 give overall average 200.0, so the result is [('b', 400.0)].
Understand the idea
A CTE (WITH name AS (...)) is a named temporary result you can use later in the same query. It lets you build a query in readable steps instead of nesting subqueries.
Worked example: a has 100, 100 and b has 400. Per model: a = 100, b = 400. The overall average of the three rows is (100 + 100 + 400) / 3 = 200, so only b is above it. The average of averages would be (100 + 400) / 2 = 250, a different threshold. With more uneven traffic, the two thresholds can flag different models.
Rule: WITH step1 AS (...), step2 AS (...) SELECT ... FROM step1, step2 WHERE ... A one-row CTE can be cross joined to every row.
Latency and cost reports, cohort analyses and multi-step metrics in ML platforms are written as chains of CTEs.
Similar problems
- Count failed training runs per project, keeping projects with zero failuresMedium
- Pick the best scoring model for each eval task with ROW_NUMBERMedium
- Pivot request statuses into columns with conditional aggregationMedium
- Find eval tasks where a candidate model scores below the baseline with a self joinMedium