【问题标题】:Groupby Multiple date time periodGroupby 多个日期时间段
【发布时间】:2021-02-10 09:13:55
【问题描述】:

我有下表,它表示特定事件每天发生的次数。

date event occurrences
2021-02-01 jumping 10
2020-08-20 walking 7
2016-01-01 swimming 1
2020-05-01 jumping 5

我想按三个不同的时间段进行分组:

  1. 最近至少发生过一次的事件 从当前日期起 3 个月
  2. 从当前日期起最近 3 个月内未发生但已发生的旧事件 从当前日期起的最后一年中至少发生过一次
  3. 从当前日期起在去年没有发生的非常古老的事件

结果表应该是

event state
jumping recent
walking old
swimming swimming

如何在 BigQuery SQL 中高效地执行此操作?

【问题讨论】:

    标签: sql google-bigquery


    【解决方案1】:

    尝试maxcase 语句:

    with testdata as (
      select date '2021-02-01' as date, 'jumping' as event, 10 as occurences union all
      select date '2020-08-20', 'walking', 7 union all
      select date '2016-01-01', 'swimming', 1 union all
      select date '2020-05-01', 'jumping', 5
    )
    select 
      event,
      case
        when max(date) < date_sub(current_date(), interval 1 year) then 'very old'
        when max(date) < date_sub(current_date(), interval 3 month) then 'old'
        else 'recent'
      end as state
    from testdata
    where occurences > 0
    group by event
    

    【讨论】:

    • 我怀疑occurrences &gt; 0 是否真的需要。我的想法是,只有在出现事件时,数据中才会出现一行(尽管 OP 对此并不清楚)。
    猜你喜欢
    • 2017-08-09
    • 2018-12-08
    • 1970-01-01
    • 2018-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多