I am pulling this query os user 'USv3s_tggf19'
in a PostgreSQL database
server.
select us.id as user_step_id, us.goal_id, us.user_id, us.created_datetime
, m.mod_code, m.modified_datetime
from database.user_steps us
left join database.mods m on
us.goal_id = m.goal_id
where us.user_id like 'USv3s_tggf19'
An this is the table that I have:
As you can see, because in the database.mods table there are duplicated records that relate to different modifications of the same thing, I end up having duplicate records in my output, which is expected.
Now, my intention is to leave the record that is closest in m.modified_date
to us.created_datetime
. And my end result should look something like this:
I’ve been trying different things looking in other responses and this query is the one that looks closest, but it does not return me anything.
select us.id as user_step_id, us.goal_id, us.user_id, us.created_datetime
, m.mod_code, m.modified_datetime
from database.user_steps us
left join database.mods m on
us.goal_id = m.goal_id
and us.created_datetime = (select max(m.modified_datetime) from database.mods m where m.modified_datetime < us.created_datetime)
where us.user_id like 'USv3s_tggf19'
I’d appreciate any guidance with this.