【问题标题】:Split a row that has data across several days by individual date (BigQuery)按单个日期拆分包含数天数据的行 (BigQuery)
【发布时间】:2021-01-21 18:59:49
【问题描述】:

我有一个数据集,其中包含有关特定类型事件的信息,包括 starttimeendtimeduration(以分钟为单位)。我想按date 对这些数据进行分组(将从starttime 中提取),但我有一行表示经过几天的事件,例如index 33、starttime 2020-07- 13 10:19:54 UTC, endtime 2020-07-15 13:13:21 UTC, and duration 3053。这一行应该分成三行,例如:

starttime          endtime            duration
2020-07-13 10:19   2020-07-13 23:59    821
2020-07-14 00:00   2020-07-14 23:59   1440
2020-07-15 00:00   2020-07-15 13:13    793

要明确的是,我正在尝试使用这 3 行来替换原来的行,所以当我按date 分组时,数字将是正确的。

如何在 BigQuery 中执行此操作?

【问题讨论】:

    标签: sql group-by google-bigquery timestamp


    【解决方案1】:

    使用genereate_date_array()unnest()

    select t.ind,
           greatest(start_ts, timestamp(dt)) as start_ts,
           least(timestamp(date_add(dt, interval 1 day)), end_ts)
    from (select 32 as ind, timestamp('2020-07-13 10:19:54 UTC') as start_ts,  timestamp('2020-07-13 13:13:21 UTC') as end_ts union all
          select 33 as ind, timestamp('2020-07-13 10:19:54 UTC') as start_ts,  timestamp('2020-07-15 13:13:21 UTC') as end_ts
         ) t cross join
         unnest(generate_date_array(date(start_ts), date(end_ts))) dt ;
    

    注意:这会将结束时间戳记为午夜,而不是前一分钟或一秒。这样,中间的日子就有 24 小时。当然,您可以减去一秒或一分钟,但这对我来说似乎不太准确。

    【讨论】:

    • 正是我需要的。谢谢!
    猜你喜欢
    • 2021-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-16
    • 1970-01-01
    • 2023-01-15
    • 1970-01-01
    • 2018-05-22
    相关资源
    最近更新 更多