If I understand correctly, then each time the outgoing
is false, you want the created_at
from preceding row with the same user_id
and state_code
.
I'm not sure how you would use the windows functions for this. Here is an approach using correlated subqueries:
Here is one way:
select t.*,
(select created_at
from t t2
where t2.user_id = t.user_id and
t2.state_code = t.state_code and
t2.outgoing = 't' and
t2.created_at < t.created_at
order by t2.created_at desc
limit 1
) as prev_created_at
from t
You can then do your date arithmetic to get what you want (mostly that prev_created_at
is not NULL
).
If you know that the previous row is the "one just before", you can do something similar with lag()
:
select t.*
from (select t.*,
lag(created_at) over (partition by user_id, state_code order by created_at) as prev_created_at,
lag(outgoing) over (partition by user_id, state_code order by created_at) as prev_outgoing
from t
) t
where t.outgoing = 'f' and t.prev_outgoing = 't';