Latest row per key (deduplicate by latest timestamp)
MediumP1Coding
Table events:
| Column | Type |
|---|---|
| id | int (primary key) |
| entity_id | int |
| status | text |
| updated_at | timestamptz |
Each entity has many rows, one per status change. Write a query that returns the latest row for every entity: the one with the greatest updated_at. If two rows of an entity share the greatest updated_at, keep the one with the larger id.
Return the columns entity_id, status and updated_at, one row per entity.
Schema
CREATE TABLE events ( id int PRIMARY KEY, entity_id int NOT NULL, status text NOT NULL, updated_at timestamptz NOT NULL );
Example 1
- Input
- events: (1, 10, 'new', '2024-01-01 09:00+00'), (2, 10, 'paid', '2024-01-02 09:00+00'), (3, 11, 'new', '2024-01-01 12:00+00')
- Output
- 10, paid, 2024-01-02 09:00:00+00 11, new, 2024-01-01 12:00:00+00
Constraints
- PostgreSQL dialect.
- Return rows in any order.
- Each entity appears exactly once in the result.
Hints
Give it a real attempt first. Run shows which examples fail.
Saved automatically
PostgreSQL
Run checks the 2 visible tests, Submit all 5. ⌘Enter runs, ⌘⇧Enter submits.