Querying sequences of rows in SQL

前端 未结 3 2248
傲寒
傲寒 2021-02-14 23:25

Suppose I am storing events associated with users in a table as follows (with dt standing in for the timestamp of the event):



        
3条回答
  •  一向
    一向 (楼主)
    2021-02-15 00:00

    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.

提交回复
热议问题