WITH ranked AS (
SELECT *,
ROW_NUMBER() OVER (
PARTITION BY entity_id
ORDER BY occurred_at DESC, event_id DESC
) AS position
FROM events
)
SELECT entity_id, event_id, occurred_at
FROM ranked
WHERE position = 1;
Keep the latest event per entity
Adapt the illustrative table and column names. The event ID breaks ties when timestamps match.