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

时间:2019-06-24 14:11:48

标签: sql postgresql gaps-and-islands

请帮助您处理请求,其中包含以下数据:您需要在状态列中将此数据分为一定间隔,以便使其大致如下所示:

data_image_example

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

1 个答案:

答案 0 :(得分:1)

这是一种扭曲的间隙和孤岛形式。您可以使用不同的行号来标识相邻的行。然后汇总并使用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;