Skip to content
Advertisement

PostgreSQL: Select latest entries only when values differ in a column

Imagine the data:

Per id, I would like to return the two latest entries of different dates (not just timestamp, the date part should be different):

I assume I need to use partition and lag on the audit_id but I don’t know how to start structuring it.

Advertisement

Answer

I would attack this in two parts. The first would make sure only the latest from a single date is kept. The second numbers the rows starting with the latest.

db<>fiddle here

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