I have a simple table with a unit_id oid, time timestamp, diag bytea. The primary key is a combination of both time and unit_id.
The idea behind this query is to get the latest row (largest timestamp) for each unique unit_id. However the rows for each unit_id with the latest time are not always returned.
I really want to group by just the unit_id, but postgres makes me use diag also, since I am selecting that.
SELECT DISTINCT ON(unit_id) max(time) as time, diag, unit_id
FROM diagnostics.unit_diag_history
GROUP BY unit_id, diag