Keep every run in the top two distinct scores per project with DENSE_RANK
Why it matters Top-n per group with ties shows up in leaderboards, retrieval re-ranking and picking the best checkpoints to keep.
A leaderboard page shows the best two score levels of each project. When runs tie, all of them should appear, so the cut is by distinct score, not by row count.
Write query() returning a SQLite SQL string. Table evals(project TEXT, run_id INTEGER, score REAL).
Return (project, run_id, score, rnk) for every run whose score is among the 2 highest DISTINCT scores of its project, where rnk is 1 for the highest score level and 2 for the next. Order by project ascending, rnk ascending, then run_id ascending.
def query()Example
project 'p' with runs (1, 0.9), (2, 0.9), (3, 0.8), (4, 0.7) gives [('p', 1, 0.9, 1), ('p', 2, 0.9, 1), ('p', 3, 0.8, 2)].
Understand the idea
Three window functions number rows in order, and they differ only on ties. For scores 0.9, 0.9, 0.8, 0.7:
ROW_NUMBER gives 1, 2, 3, 4 (ties broken arbitrarily or by an extra sort key).
RANK gives 1, 1, 3, 4 (ties share, then a gap).
DENSE_RANK gives 1, 1, 2, 3 (ties share, no gap).
So 'top 2 distinct scores' is DENSE_RANK <= 2, which keeps the two 0.9 runs and the 0.8 run. ROW_NUMBER <= 2 would keep only the two 0.9 runs, and RANK <= 2 would also miss 0.8.
Rule: pick the numbering by the question. Exactly n rows per group: ROW_NUMBER. Top n score levels with all ties: DENSE_RANK.
Leaderboards, checkpoint pruning and per-query top-k retrieval reports all need this choice.
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