Keep the latest annotation per item, then count labels
Why it matters Dedupe-latest is the standard way to read slowly changing tables: labels, user profiles, model registry entries.
Annotators often relabel the same item. A label distribution must use only the latest label per item, or relabeled items are counted twice.
Write query() returning a SQLite SQL string. Table annotations(id INTEGER, item_id INTEGER, label TEXT, created_at TEXT) where created_at is an ISO timestamp.
For each item keep the row with the latest created_at; if two rows share it, keep the larger id. Then return (label, n_items) over the kept rows. Order by n_items descending, then label ascending.
def query()Example
(1, 10, 'neg', '2026-01-01'), (2, 10, 'pos', '2026-01-02'), (3, 11, 'pos', '2026-01-01') give [('pos', 2)].
Understand the idea
Many tables keep history: every change is a new row. To read the current state you keep one row per key, the newest. ROW_NUMBER partitioned by the key and ordered newest first does it, and a CTE keeps the query readable.
Worked example: item 10 has 'neg' on Jan 1 and 'pos' on Jan 2. Ordered newest first, 'pos' gets rn = 1 and 'neg' gets rn = 2. Item 11 has one row, 'pos', rn = 1. Keeping rn = 1 leaves two 'pos' items, so the result is [('pos', 2)].
Rule: WITH t AS (SELECT ..., ROW_NUMBER() OVER (PARTITION BY key ORDER BY ts DESC, id DESC) AS rn FROM tbl) SELECT ... FROM t WHERE rn = 1. Always add a unique tie-breaker so the result is deterministic.
Label stores, feature tables and model registries are read this way.
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