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;