如何按条件将日期转换为日期范围(postgres)

How convert dates to dates range by condition (postgres)

求助一下,有这样的数据:你需要把这个数据分成区间,在状态栏,这样大概是这样的:

client| date_start        | date_end          | status
-------------------------------------------------------
1     | 01.06.2019 0:00:00| 01.06.2019 0:02:00| 2
1     | 01.06.2019 0:02:00| 01.06.2019 0:04:00| 1
1     | 01.06.2019 0:04:00| 01.06.2019 0:05:00| 2

这是 gaps-and-islands 的一种变形形式。您可以使用行号的差异来识别相邻的行。然后聚合,用lead()得到结束时间:

select client, status, min(time) as starttime,
       lead(min(time)) over (partition by client order by min(time)) as endtime
from  (select t.*,
              row_number() over (partition by client order by time) as seqnum,
              row_number() over (partition by client, status order by time) as seqnum_s
       from t
      ) t
group by (seqnum - seqnum_s), status, client;