• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home ยป Resolved: PostgreSQL: Select latest entries only when values differ in a column

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

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

Question:

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.

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.

with by_day as (
select *,
updated_at::date !=
lag(updated_at::date) over (partition by id
order by updated_at desc) keep
from imagined_data
), numbered as (
select *, row_number() over (partition by id
order by updated_at desc) as rn
from by_day
where coalesce(keep, true)
)
select id, audit_id, val, updated_at
from numbered
where rn <= 2; [/code]

db<>fiddle here

If you have better answer, please add a comment about this, thank you!

date 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.