加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

用Postgresql合并连续的行

发布时间:2020-12-13 16:32:27 所属栏目:百科 来源:网络整理
导读:我有一个这样的插槽表: Column | Type |------------+-----------------------------+ id | integer | begin_at | timestamp without time zone | end_at | timestamp without time zone | user_id | integer | 我喜欢连续选择合并的行.假设我有(简化的)数
我有一个这样的插槽表:
Column   |            Type             |
------------+-----------------------------+
 id         | integer                     |
 begin_at   | timestamp without time zone |
 end_at     | timestamp without time zone |
 user_id    | integer                     |

我喜欢连续选择合并的行.假设我有(简化的)数据,如:

(1,5:15,5:30,1)
(2,2)
(3,5:45,2)
(4,6:00,2)
(5,8:15,8:30,2)
(6,8:45,2)

我想知道是否可以选择格式如下的行:

(5:15,1)
(5:15,2) // <======= rows id 2,3 and 4 merged
(8:15,2) // <======= rows id 5 and 6 merged

编辑:
这是SQLfiddle

我使用Postgresql 9.3版本!

谢谢!

这是解决这个问题的一种方法.创建一个标志,确定一条记录是否与上一条记录不重叠.这是一个小组的开始.然后取这个标志的累积和,并将其用于分组:
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是一个SQL小提琴.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读