Merge continuous rows with Postgresql

前端 未结 2 1485
没有蜡笔的小新
没有蜡笔的小新 2021-02-13 18:35

I have a slots table like this :

   Column   |            Type             |
------------+-----------------------------+
 id         | integer               


        
2条回答
  •  借酒劲吻你
    2021-02-13 19:17

    Here is one method for solving this problem. Create a flag that determines if a one record does not overlap with the previous one. This is the start of a group. Then take the cumulative sum of this flag and use that for grouping:

    select user_id, min(begin_at) as begin_at, max(end_at) as end_at
    from (select s.*, sum(startflag) over (partition by user_id order by begin_at) as grp
          from (select s.*,
                       (case when lag(end_at) over (partition by user_id order by begin_at) >= begin_at
                             then 0 else 1
                        end) as startflag
                from slots s
               ) s
         ) s
    group by user_id, grp;
    

    Here is a SQL Fiddle.

提交回复
热议问题