【问题标题】:comparing timestamps in two consecutive rows which have different values for column A and the same value for column B in Big Query比较 Big Query 中 A 列具有不同值而 B 列具有相同值的两个连续行中的时间戳
【发布时间】:2020-03-31 21:46:38
【问题描述】:

伙计们,我有一个很大的查询结果,它显示了骑手(在rider_id 列中)退出应用程序(event 列)的时间(在local_time 列中),所以有两个event、“authentication_complete”和“logout”列的不同值。

event_date  rider_id    event                    local_time
20200329    100695      authentication_complete  20:07:09
20200329    100884      authentication_complete  12:00:51
20200329    100967      logout                   10:53:17
20200329    100967      authentication_complete  10:55:24
20200329    100967      logout                   11:03:28
20200329    100967      authentication_complete  11:03:47
20200329    101252      authentication_complete  7:55:21
20200329    101940      authentication_complete  8:58:44
20200329    101940      authentication_complete  17:19:57
20200329    102015      authentication_complete  14:20:27
20200329    102015      logout                   22:47:50
20200329    102015      authentication_complete  22:48:34

我想要实现的是每个曾经退出的骑手,在一个列中我想获得他们退出的时间,在另一列中我想获得紧随其后的事件“authentication_complete”的时间该骑手的注销事件。通过这种方式,我可以看到每个骑手离开应用程序的时间段。我想得到的查询结果如下所示。

event_date  rider_id    time_of_logout  authentication_complete_right_after_the_logout
20200329    100967      10:53:17        10:55:24
20200329    100967      11:03:28        11:03:47
20200329    102015      22:47:50        22:48:34

这是一个非常不干净的数据集,到目前为止我能够清理这么多,但是到了这一步,我感觉很卡。我正在研究像 lag() 这样的函数,但是由于数据是 180,000 行,对于一个 Rider_id,可以有多个名为“logout”的事件,并且对于同一个 Rider_id,有多个名为“authentication_complete”的连续事件,这更加令人困惑。我真的很感激任何帮助。谢谢!

【问题讨论】:

  • 如果下一个事件不是认证怎么办?
  • 下一个事件几乎总是“authentication_complete”。 “注销”之后的下一个事件再次“注销”的情况很少,但这是由于数据不完整而导致的一方,在这种情况下,我们可以只查看下一个最早的事件“authentication_complete”或忽略嫌麻烦就去吧

标签: sql google-bigquery data-cleaning data-wrangling


【解决方案1】:

我想你想要lead():

select event_date, rider_id, date, local_time as logout_date,
       authentication_date
from (select t.*,
             lead(local_time) over (partition by event_date, rider_id order by local_time) as authentication_date
      from t
     ) t
where event = 'logout';

这假设下一个事件确实是身份验证,如您的示例数据中所示。如果不是这种情况,您无需指定该怎么做。

如果您特别想要下一个身份验证日期,则可以使用min()

select event_date, rider_id, date, local_time as logout_date,
       authentication_date
from (select t.*,
             min(case when event = 'authentication_complete' then local_time end) over (partition by event_date, rider_id order by local_time desc) as authentication_date
      from t
     ) t
where event = 'logout';

【讨论】:

  • 您分享的第一个查询实际上运行良好!谢谢!但第二个实际上是在注销之前而不是之后给出 authentication_complete。
  • 应该有一个desc 在那个order by。我修好了。
猜你喜欢
  • 2021-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-02
  • 2011-09-18
  • 2012-05-25
相关资源
最近更新 更多