Table event has id, created and some other columns, but only those are relevant here. The query above gives me id of last event generated per given trunc time period (thanks to DISTINCT ON I get a nice aggregation per period).

Now, this query yields NULL if no events happened in given time period. I would like it to return the previous available id, even if it is from different time period. I.e.:

with cte as (
select
t1.a,
coalesce( t1.b, t2.b, 0) as b,
rank() OVER
(PARTITION BY t1.a ORDER BY t2.a DESC) as pos
from t t1
left outer join t t2
on t2.b is not null and
t2.a < t1.a
)
select a, b
from cte
where pos = 1;