• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home ยป Resolved: Retrieve SQL records where only the last unique entries match criteria in postgresql

Resolved: Retrieve SQL records where only the last unique entries match criteria in postgresql

0
By Isaac Tonny on 17/06/2022 Issue
Share
Facebook Twitter LinkedIn

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:
When I want to look for a list of devices and see their ‘history’, I know I can use something like:
What I am really looking for is a query that returns a unique list of devices where the latest dated entry for each device only contains a state of ‘4’ (‘inactive state’), and not include records that do not match.
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:
with obviously no success.
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:

The 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!

distinct-values postgresql sql
Share. Facebook Twitter LinkedIn

Related Posts

Resolved: std::regex_replace to replace multiple combinations

26/03/2023

Resolved: How can I copy files using the ansible.builtin.copy module and avoid conflicting file names?

26/03/2023

Resolved: Reshape tensors of unknown shape with tf.function

26/03/2023

Leave A Reply

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.