Suppose I am storing events
associated with users
in a table as follows (with dt
standing in for the timestamp of the event):
With Postgres 9.x this is actually quite easy:
select userid,
string_agg(event, '' order by dt) as event_sequence
from events
group by userid;
Using that result you can now apply a regular expression on the event_sequence:
select *
from (
select userid,
string_agg(event, '' order by dt) as event_sequence
from events
group by userid
) t
where event_sequence ~ 'A.*B'
With Postgres 8.x you need to find a replacement for the string_agg() function (just google for it, there are a lot of examples out there) and you need a sub-select to ensure the ordering of the aggregate as 8.x does support an order by
in an aggregate function.