gpt4 book ai didi

sql - PostgreSQL:如何根据相同的开始和结束时间(没有时区的时间戳)连接两个表?

转载 作者:行者123 更新时间:2023-11-29 13:47:28 24 4
gpt4 key购买 nike

好的,我遇到了this相关问题,但与我的情况略有不同。

问题

我的 PostgreSQL 9.5 数据库中有两个相似类型的表 tbl1tbl2都包含 1,274 rows . table 1的结构与布局如下:

表 1:

id (integer)   start_time           end_time              my_val1 (numeric)
51 1994-09-26 16:50:00 1994-10-29 13:30:00 3.7
52 1994-10-29 13:30:00 1994-11-27 12:30:00 2.4
53 1994-11-27 12:30:00 1994-12-29 09:25:00 7.6
54 1994-12-29 09:25:00 1994-12-31 23:59:59 2.9
54 1995-01-01 00:00:00 1995-02-05 13:50:00 2.9
55 1995-02-05 13:50:00 1995-03-12 11:10:00 1.6
56 1995-03-12 11:10:00 1995-04-11 09:05:00 2.2
171 1994-10-29 16:15:00 1994-11-27 19:10:00 6.9
172 1994-11-27 19:10:00 1994-12-29 11:40:00 4.2
173 1994-12-29 11:40:00 1994-12-31 23:59:59 6.7
173 1995-01-01 00:00:00 1995-02-05 15:30:00 6.7
174 1995-02-05 15:30:00 1995-03-12 09:45:00 3.2
175 1995-03-12 09:45:00 1995-04-11 11:30:00 1.2
176 1995-04-11 11:30:00 1995-05-11 15:30:00 2.7
321 1994-09-26 14:40:00 1994-10-30 14:30:00 0.2
322 1994-10-30 14:30:00 1994-11-27 14:45:00 7.8
323 1994-11-27 14:45:00 1994-12-29 14:20:00 4.6
324 1994-12-29 14:20:00 1994-12-31 23:59:59 4.1
324 1995-01-01 00:00:00 1995-02-05 14:35:00 4.1
325 1995-02-05 14:35:00 1995-03-12 11:30:00 8.2
326 1995-03-12 11:30:00 1995-04-11 09:45:00 1.2
.....

在某些行中,start_timeend_time可能看起来相似,但整个时间窗口可能不相等。例如,

 id (integer)   start_time          end_time              my_val1 (numeric)
54 1994-12-29 09:25:00 1994-12-31 23:59:59 2.9
173 1994-12-29 11:40:00 1994-12-31 23:59:59 6.7

Start_timeend_timetimestamp without time zone . start_timeend_time必须在一年的窗口中,因此无论何时从 1994 发生变化至 1995然后该行被分成两行,因此,列中有重复的 ID id .表 2 tbl2包含类似的 start_timeend_time ( timestamp without time zone ) 和列 my_val2 (numeric)。对于 table 1 中的每一行我需要加入 table 2 的相应行其中 start_timeend_time相似。

我试过的,

Select 
a.id,
a.start_time, a.end_time,
a.my_val1,
b.my_val2
from tbl1 a
left join tbl2 b on
b.start_time = a.start_time
order by a.id;

查询返回3,802不需要的行。期望的结果是 1,274 行 table 1加入my_val2 .我知道 Postgres Distinct on条款,但我需要保持所有重复idstbl1并且只需要加入my_val2tbl2 .我需要在这里使用 Postgres Window 函数吗?有人可以建议如何加入这两个表吗?

最佳答案

为什么不在 ON 部分添加条件

ON b.start_time = a.start_time AND a.id = b.id

关于sql - PostgreSQL:如何根据相同的开始和结束时间(没有时区的时间戳)连接两个表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46062514/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com