SQL: Greatest N per Group

I run into this quite a bit. You have an auto incrementing row where you are interested in the last (most recent) entry made for a group of records.

SELECT a.*
FROM YourTable a
LEFT OUTER JOIN YourTable b
    ON a.id = b.id AND a.rev < b.rev
WHERE b.id IS NULL;

Leave a comment

Your email address will not be published. Required fields are marked *