有没有办法使用sql查询将一个时间序列数据表重叠到另一个时间序列数据表上?

有没有办法使用sql查询将一个时间序列数据表重叠到另一个时间序列数据表上?,sql,database,postgresql,time-series,Sql,Database,Postgresql,Time Series,希望我能在这里找到我的难题的答案 我在Postgres DB中有两个表,我想在另一个表上重叠 表A有3列:开始时间、结束时间和状态。在每一行中,开始时间等于前一行的结束时间 表B有相同的列,但开始和结束时间不相邻,也不重叠 我想将表B重叠到表A上以创建表C 表C中每一行的开始时间也等于前一行的结束时间 下面是一个例子来说明: 表A-受影响者 状态 开始时间 结束时间 1. 上午12:00:00 上午12:10:00 2. 上午12:10:00 上午12:20:00 1. 上午12:20:00 上

希望我能在这里找到我的难题的答案

我在Postgres DB中有两个表,我想在另一个表上重叠

表A有3列:开始时间、结束时间和状态。在每一行中,开始时间等于前一行的结束时间

表B有相同的列,但开始和结束时间不相邻,也不重叠

我想将表B重叠到表A上以创建表C

表C中每一行的开始时间也等于前一行的结束时间

下面是一个例子来说明:

表A-受影响者

状态 开始时间 结束时间 1. 上午12:00:00 上午12:10:00 2. 上午12:10:00 上午12:20:00 1. 上午12:20:00 上午12:30:00 2. 上午12:30:00 上午12:40:00 1. 上午12:40:00 上午12:50:00 2. 上午12:50:00 凌晨1:00:00
一种方法是提取所有开始时间和结束时间,然后在该开始时间提取正确的状态,并使用lead获取结束时间:

with t as (
      select starttime as tm
      from a
      union  -- on purpose to remove duplicates
      select endtime
      from a
      union 
      select starttime as tm
      from b
      union  -- on purpose to remove duplicates
      select endtime
      from b
     )
select t.tm, lead(t.tm) over (order by t.tm) as endtime,
       (select ab.state
        from ((select a.*
               from a
              ) union all
              (select b.*
               from b
              )
             ) ab
        where ab.starttime <= t.tm and t.tm < ab.endtime
        order by ab.starttime desc
        limit 1
       ) as state
from t;

一种方法是提取所有开始时间和结束时间,然后在该开始时间提取正确的状态,并使用lead获取结束时间:

with t as (
      select starttime as tm
      from a
      union  -- on purpose to remove duplicates
      select endtime
      from a
      union 
      select starttime as tm
      from b
      union  -- on purpose to remove duplicates
      select endtime
      from b
     )
select t.tm, lead(t.tm) over (order by t.tm) as endtime,
       (select ab.state
        from ((select a.*
               from a
              ) union all
              (select b.*
               from b
              )
             ) ab
        where ab.starttime <= t.tm and t.tm < ab.endtime
        order by ab.starttime desc
        limit 1
       ) as state
from t;

棒极了,按预期工作。谢天谢地,一切如愿。谢谢