Keep the latest annotation per item, then count labels

MediumSQL

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.

Signaturedef 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.

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: relabeled items_run2(query())
  • Test 3: same timestamp, larger id wins_run3(query())