Sql 从开始时间和结束时间之间的时间戳返回值数组

Sql 从开始时间和结束时间之间的时间戳返回值数组,sql,postgresql,datetime,Sql,Postgresql,Datetime,我有一个查询,它生成一个时间戳和该时间戳上的一个值 select timestamp, value from table1; 因此,数据样本如下所示: timestamp | value | --------------------------------------- 2019-02-28 01:00:00 | 1 | 2019-02-28 01:10:00 | 1 | 2019-02-28 0

我有一个查询,它生成一个时间戳和该时间戳上的一个值

select timestamp, value
from table1;
因此,数据样本如下所示:

      timestamp      |     value      |
---------------------------------------
 2019-02-28 01:00:00 | 1              |
 2019-02-28 01:10:00 | 1              |
 2019-02-28 01:20:00 | 6              |
 2019-02-28 01:30:00 | 17             |
 2019-02-28 01:40:00 | 4              |
 2019-02-28 01:50:00 | 4              |
       start        |         end         |
-------------------------------------------
2019-02-28 01:00:00 | 2019-02-28 01:30:00 |
2019-02-28 01:40:00 | 2019-02-28 01:50:00 |
我有第二个查询,它生成开始时间戳和结束时间戳

select start, end
from table2;
其中的一个示例如下所示:

      timestamp      |     value      |
---------------------------------------
 2019-02-28 01:00:00 | 1              |
 2019-02-28 01:10:00 | 1              |
 2019-02-28 01:20:00 | 6              |
 2019-02-28 01:30:00 | 17             |
 2019-02-28 01:40:00 | 4              |
 2019-02-28 01:50:00 | 4              |
       start        |         end         |
-------------------------------------------
2019-02-28 01:00:00 | 2019-02-28 01:30:00 |
2019-02-28 01:40:00 | 2019-02-28 01:50:00 |
我怎样才能组合这两个查询来生成这样的输出

       start        |         end         |      values     |
-------------------------------------------------------------
2019-02-28 01:00:00 | 2019-02-28 01:30:00 | {1,1,6}         |
2019-02-28 01:40:00 | 2019-02-28 01:50:00 | {4}             |

聚合和加入:

select t2.start, t2.end, array_agg(t1.value)
from table2 t2 left join
     table1 t1
     on t1.timestamp >= t2.start and t1.timestamp < t2.end
group by t2.start, t2.end;
选择t2.start、t2.end、数组_agg(t1.value)
从表2中t2左连接
表1 t1
在t1.timestamp>=t2.start和t1.timestamp
谢谢!你知道这是否也适用于两个临时表吗?@hov。临时表与逻辑无关。这将适用于临时表、永久表、视图、CTE和子查询。