【问题标题】:Add derived column from existing column based on a condition in bigquery根据 bigquery 中的条件从现有列添加派生列
【发布时间】:2022-11-22 17:16:32
【问题描述】:

假设我们有下表

user_id event_name event_time
Adam subscribe 1
Adam renewal 4
Adam renewal 5
Adam churn 7
Adam subscribe 10
Adam renewal 20

笔记:

我想为每一行添加数字,以便最终表格如下所示:

user event_name event_time subscription_time
Adam subscribe 1 1
Adam renewal 4 1
Adam renewal 5 1
Adam churn 7 1
Adam subscribe 10 10
Adam renewal 20 10
Adam renewal 30 10
Adam churn 40 10

解释一下,每个续订事件都属于前一个订阅事件。我需要一个派生列来显示该订阅事件的时间。因此派生列应该与该事件的订阅时间相同。我的最终目的是找出给定订阅时间的续订/流失等数量

希望我能很好地解释我的问题。 感谢您付出的努力和时间。

【问题讨论】:

    标签: sql google-bigquery


    【解决方案1】:

    考虑以下类似于我之前的回答的方法。

    SELECT *,
           IF(event_name IN ('subscribe', 'renewal', 'churn'),
              -- below will return most recent time of *subscribe* event
              LAST_VALUE(IF(event_name = 'subscribe', event_time, NULL) IGNORE NULLS) OVER (PARTITION BY user ORDER BY event_time),
              NULL
           ) AS subscription_time
      FROM sample_table;
    

    查询结果

    【讨论】:

      猜你喜欢
      • 2014-09-20
      • 2020-04-30
      • 2019-08-17
      • 2013-01-18
      • 1970-01-01
      • 1970-01-01
      • 2016-02-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多