微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在 SQL 中最近的日期加入

如何解决在 SQL 中最近的日期加入

嗨,我有两个表,我必须在 ID 字段上加入,然后在最近的日期(仅当日期在一个小时范围内或多或少时),原因是两个表没有同时更新,所以时间是两者之间相差不大(但最大延迟为 1 小时)。请看下面的例子:

表 1:

ID Start_Date         End_Date
1  1/14/2021 14:34    1/27/2021 10:31
1  2/4/2021 10:40     7/2/2021 13:01
2  8/2/2020 00:04      9/7/2020 11:26
2  11/4/2020 9:24     2/8/2021 16:22

表 2:

ID Start_date         End_Date
1  1/14/2021 13:47    1/27/2021 10:24
2  8/1/2020 23:57      9/7/2020 11:22
2  11/4/2020 9:12     2/8/2021 16:20

在这个例子中:表 1 中的记录 1 应该连接到表 2 中的记录 1。

表 1 中的记录 2 不应连接到表 2(因为该 ID 的 1 小时开始日期内没有记录) 记录3,4应该分别连接到表2中的记录3,4。

解决方法

免责声明:我不是 Snowflake 方面的专家,也无法测试下面描述的解决方案。

假设您可以在 Snowflake 中使用标准 SQL,下面的查询会预先计算可能相关行的起始日期之间的时间差,并将它们从低到高排列。最低(最小时间差)赢得加入。

你可以这样做:

select *
from (
  select
    a.*,b.*,row_number() over(
      partition by a.id
      order by abs(timediff(second,a.start_date,b.start_date))
    ) as rn
  from table1 a
  join table2 b on a.id = b.id
   and a.start_date between dateadd(hour,-1,b.start_date) 
                        and dateadd(hour,1,b.start_date)
) x
where rn = 1
,

另一种选择可能是:

select *  from  table_1 inner join table_2 on table_1.id = table_2.id 
where      DATEADD(hour,table_1.d_1)   between table_2.d_1 and table_2.d_2  
or         DATEADD(hour,table_1.d_2)  between table_2.d_1 and table_2.d_2

enter image description here

您可以剪切/粘贴到雪花中并运行的完整代码:-)

with table_1 as ( 
select 1 id,TO_TIMESTAMP('1/14/2021 14:34','mm/dd/yyyy hh24:mi' ) d_1,TO_TIMESTAMP('1/27/2021 10:31','mm/dd/yyyy hh24:mi' )  d_2 
union select 1 id,TO_TIMESTAMP('2/4/2021 10:40','mm/dd/yyyy hh24:mi' )  d_1,TO_TIMESTAMP('7/2/2021 13:01','mm/dd/yyyy hh24:mi' )  d_2 
union select 2 id,TO_TIMESTAMP('8/2/2020 00:04',TO_TIMESTAMP('9/7/2020 11:26',TO_TIMESTAMP('11/4/2020 9:24',TO_TIMESTAMP('2/8/2021 16:22','mm/dd/yyyy hh24:mi' )  d_2 ),table_2 as ( 
select 1 id,TO_TIMESTAMP('1/14/2021 13:47','mm/dd/yyyy hh24:mi' ) 
d_1,TO_TIMESTAMP('1/27/2021 10:24',TO_TIMESTAMP('8/1/2020 23:57',TO_TIMESTAMP('9/7/2020 11:22',TO_TIMESTAMP('11/4/2020 9:12',TO_TIMESTAMP(' 2/8/2021 16:20','mm/dd/yyyy hh24:mi' )  d_2   ) 

select *  from  table_1 inner join table_2 on table_1.id = table_2.id 
where      DATEADD(hour,table_1.d_2)  between table_2.d_1 and table_2.d_2 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。