Skip to content
Advertisement

Postgres SQL Select two fields by most recent date, one field must be unique

I need to find which student belongs to which homeroom, as of the latest data inputted.

Starting with this dataset:

I want to only retrieve Alice’s most recent homeroom and Bob’s most recent homeroom:

The typical answer of how to find the most recent record only applies to when you’re looking for one field’s recency:

This is not what I want:

Advertisement

Answer

You can use distinct on:

distinct on is a very handy Postgres extension. It returns on row for the keys in the distinct on list. The row is based on the ordering criteria in the order by.

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