Skip to content
Advertisement

Obtain latest record for a given second Postgres

I have data with millisecond precision timestamp. I want to only filter for the most recent timestamp within a given second. Ie. records (2020-07-13 5:05.38.009, event1), (2020-07-13 5:05.38.012, event2) should only retrieve the latter.

I’ve tried the following:

SELECT 
    timestamp as time, event as value, event_type as metric 
FROM 
    table
GROUP BY 
    date_trunc('second', time)

But then I’m asked to group by event as well and I see all the data (as if no group by was provided)

Advertisement

Answer

In Postgres, you can use distinct on:

select distinct on (date_trunc('second', time)) t.*
from t
order by time desc;
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement