检查亚马逊 Athena / Presto 中两个间隔是否重叠的方法

way to check if two intervals overlap in amazon Athena / Presto

我想知道我们是否有办法检查 amazon athena 中的两个日期是否重叠(在编写 athena 查询时)。我可以使用 int_overlaps 和间隔函数在 R / Python 中执行此操作。 例如下面 int_overlaps(间隔(LeadStart, LeadEnd), 间隔(MinStartDate, MaxEndDate)))

Min、Max、Lead 只是应用于数据帧中列的标准 R 函数。g Minstartdate <- Min(startdate)

我想在 amazon athena 中重复相同的过程,我有两个日期间隔,并检查它们是否重叠,如果重叠,我想在新列中得到 1 或 0 的布尔结果 (就像 R 中的 mutate 函数,如果日期重叠或不重叠则放置 1 或 0)

谢谢 哈里斯

假设 LeadStart <= LeadEndMinStartDate <= MaxEndDate,检查日期重叠的 SQL 表达式将是:

NOT (LeadEnd < MinStartDate OR MaxEndDate < LeadStart)

即英语:NOT(第一个在第二个开始之前结束或第二个在第一次开始之前结束)。

等价的表达式(随便你喜欢哪个):

LeadEnd >= MinStartDate AND MaxEndDate >= LeadStart

如果您有两个时间间隔以及时间间隔 (1) 和时间间隔 (2) 的相应开始和结束时间,并且您想检查它们之间是否存在重叠(在 Athena Presto 中):

with t0 as (
select *
from (
values
     ('02:00:00', '08:00:00', '01:00:00', '03:00:00'
      ), 
     ('02:00:00', '08:00:00', '03:00:00', '05:00:00'
      ), 
     ('02:00:00', '08:00:00', '05:00:00', '10:00:00'
      ), 
     ('02:00:00', '08:00:00', '10:00:00', '15:00:00'
      ), 
     ('02:00:00', '08:00:00', '01:00:00', '10:00:00'
      ), 
     ('02:00:00', '08:00:00', '00:00:00', '01:00:00'
      )
) AS t0 (start_time_1, end_time_1, start_time_2, end_time_2)
)

select * , 
case when (start_time_2 <= start_time_1 and end_time_2 >= start_time_1) 
     then 1
     when (start_time_2 >= start_time_1 and start_time_2 <= end_time_1) 
     then 1
     else 0 
     end as time_overlap
from t0