Google bigquery 在SQL中,计算开始和结束之间的时间差;结束时间戳,跨越多个重叠凸面

Google bigquery 在SQL中,计算开始和结束之间的时间差;结束时间戳,跨越多个重叠凸面,google-bigquery,timestamp,Google Bigquery,Timestamp,努力为这篇文章找到一个合适的标题。我们有一个人与许多用户的对话数据。表中的每一行都有此人和用户之间的一次对话的开始时间和结束时间,如下所示: with start_end_table as ( select TIMESTAMP("2007-12-31 12:00:00+00") as startTime, TIMESTAMP("2007-12-31 12:05:00+00") as endTime union al

努力为这篇文章找到一个合适的标题。我们有一个人与许多用户的对话数据。表中的每一行都有此人和用户之间的一次对话的开始时间和结束时间,如下所示:

    with start_end_table as (
        select TIMESTAMP("2007-12-31 12:00:00+00") as startTime, TIMESTAMP("2007-12-31 12:05:00+00") as endTime 
        union all 
        select TIMESTAMP("2007-12-31 12:03:00+00") as startTime, TIMESTAMP("2007-12-31 12:17:00+00") as endTime
        union all
        select TIMESTAMP("2007-12-31 12:07:00+00") as startTime, TIMESTAMP("2007-12-31 12:15:00+00") as endTime
        union all
        select TIMESTAMP("2007-12-31 12:24:00+00") as startTime, TIMESTAMP("2007-12-31 12:31:00+00") as endTime
        union all
        select TIMESTAMP("2007-12-31 12:29:00+00") as startTime, TIMESTAMP("2007-12-31 12:36:00+00") as endTime
        union all
        select TIMESTAMP("2007-12-31 12:41:00+00") as startTime, TIMESTAMP("2007-12-31 12:46:00+00") as endTime
    )
    
    select
        *,
        timestamp_diff(endTime, startTime, minute) as diffTime
    from start_end_table

这些聊天当前按开始时间顺序排列。如果我们在电子表格中可视化这些聊天,我们会看到一些聊天重叠(每列代表1分钟):

如您所见,前3个车队之间以及车队4和车队5之间存在一些重叠。虽然所有6次聊天时间的总和为5+14+8+7+7+5=46分钟(从12:00到12:46),但此人实际上只花了34分钟与用户聊天,因为12分钟(从12:17到12:24的7分钟,从12:36到12:41的5分钟)没有花在聊天上


是否可以从我们拥有的SQL表
start\u end\u表
计算这34分钟?我正在努力想出一个解决方案来解决这个问题。

考虑以下方法-首先将所有时间间隔拆分为分钟,然后在所有时间间隔中计算不同的分钟数

select count(distinct minute_spent) total_minutes_spent
from (
  select minute_spent from start_end_table, 
  unnest(generate_timestamp_array(
    startTime, timestamp_sub(endTime, interval 1 minute), interval 1 minute
  )) minute_spent
)