Skip to content
Advertisement

Last Row In Group Based on Timestamp Column For a Subset of Group Ids – Postgres

Given a postgres table of the following form:

What is the SQL query to retrieve the last row for a subset of group ids based on the timestamp column?

For example, retrieving the last row for group ids {1,3} to produce:

Thank you in advance for your consideration and response

Advertisement

Answer

A simple and efficient method to solve this greatest-n-per-group problem in Postgres is to use distinct on:

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement