简体   繁体   English

根据 bigquery 中的条件从现有列添加派生列

[英]Add derived column from existing column based on a condition in bigquery

Suppose we have table below假设我们有下表

user_id用户身份 event_name事件名称 event_time事件时间
Adam亚当 subscribe订阅 1 1个
Adam亚当 renewal更新 4 4个
Adam亚当 renewal更新 5 5个
Adam亚当 churn搅动 7 7
Adam亚当 subscribe订阅 10 10
Adam亚当 renewal更新 20 20

Notes:笔记:

I wanted to add numbers for each row so that final table looks like this:我想为每一行添加数字,以便最终表格如下所示:

user用户 event_name事件名称 event_time事件时间 subscription_time订阅时间
Adam亚当 subscribe订阅 1 1个 1 1个
Adam亚当 renewal更新 4 4个 1 1个
Adam亚当 renewal更新 5 5个 1 1个
Adam亚当 churn搅动 7 7 1 1个
Adam亚当 subscribe订阅 10 10 10 10
Adam亚当 renewal更新 20 20 10 10
Adam亚当 renewal更新 30 30 10 10
Adam亚当 churn搅动 40 40 10 10

To explain, each renewal event belongs to preceding subscribe event.解释一下,每个续订事件都属于前一个订阅事件。 I need a derived column that shows the time for that subscription event.我需要一个派生列来显示该订阅事件的时间。 Therefore derived column should be same as a subscription time of that event.因此派生列应该与该事件的订阅时间相同。 My final purpose is to find out number of renewals/churns etc for a given subscription time我的最终目的是找出给定订阅时间的续订/流失等数量

Hope i explained my question well.希望我能很好地解释我的问题。 Thanks for your effort and time.感谢您付出的努力和时间。

Consider below approach similar to previous my answer.考虑以下类似于我之前的回答的方法。

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;

Query results查询结果

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM