Question:
I’ve got a long table that tracks a numerical ‘state’ value (0=new, 1=setup mode, 2=retired, 3=active, 4=inactive) of a collection of ‘devices’ historically. These devices may be activated/deactivated throughout the year, so the table is continuous collection of state changes – mostly state 3 and 4, ordered by id, with a timestamp on the end, for example:So in using the above data samples, even though both devices 2345 and 2351 have states of 3 and 4 throughout their history, only device 2351 has it’s last dated entry with a state of 4 – meaning it is currently in an ‘inactive’ state. Device 2345’s would not appear in the result set since its last dated entry has a state of 3 – it’s still active.
Stabbing in the dark, I’ve tried variants of:
I’m thinking I might need to ‘group’ the entries together, but I don’t know how to specify ‘return last entry only if new_state = 4′ in SQL, or rather PostgreSQL.
Any tidbits or pokes in the right direction would be appreciated.
Answer:
DISTINCT ON
keyword together with the ORDER BY
will pull the newest row for each device. The outer query then filters these by your condition.If you have better answer, please add a comment about this, thank you!