Skip to content
Advertisement

SQL group by a field and only return one joined row for each grouping

Table data

What I want to do is group by the name, then for each group choose one of the rows with the earliest required by date.

For this data set, I would like to end up with either rows 1 and 4, or rows 2 and 4.

Expected result:

OR

I have something that returns 1,2 and 4 but I’m not sure how to only pick one from the first group to get the desired result. I’m joining the grouping with the data table so that I can get the ID and another_field back after the grouping.

Advertisement

Answer

This is typically solved using window functions:

In Postgres using distinct on() is typically faster:

Online example

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