【问题标题】:In SQL, compute time differences between start & end timestamps, across multiple overlapping converations在 SQL 中,跨多个重叠对话计算开始和结束时间戳之间的时间差
【发布时间】:2023-03-17 13:56:01
【问题描述】:

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

    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 个 convos 之间以及 convos 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_end_table 计算这 34 分钟?我正在努力想出一个适用于此的解决方案。

【问题讨论】:

    标签: google-bigquery timestamp


    【解决方案1】:

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

    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
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多