BigQuery 中的条件递增
Conditional incrementing in BigQuery
我有这样的数据table:
user_id event_time
1 1456812346
1 1456812350
1 1456812446
1 1456812950
1 1456812960
现在,我正在尝试根据 event_time 为用户定义一个 'session_id'。如果事件在 180 秒的滞后后出现,则事件被视为来自新会话。所以,我想要类似于以下的输出:
user_id event_time session_id
1 1456812346 1
1 1456812350 1
1 1456812446 1
1 1456812950 2
1 1456812960 2
会话在第 4 行递增,因为第 3 行之后的时间是 504 秒,因此超过了 180 秒的阈值。
在Mysql中,我可以只声明一个变量然后有条件地递增它。由于 BigQuery 不支持创建变量,是否有其他方法可以实现此目的?
SELECT
user_id, event_time, session_id
FROM (
SELECT
user_id, event_time, event_time - last_time > 180 AS new_session,
SUM(IFNULL(new_session, 1))
OVER(PARTITION BY user_id ORDER BY event_time) AS session_id
FROM (
SELECT user_id, event_time,
LAG(event_time) OVER(PARTITION BY user_id ORDER BY event_time) AS last_time
FROM YourTable
)
)
ORDER BY event_time
我有这样的数据table:
user_id event_time
1 1456812346
1 1456812350
1 1456812446
1 1456812950
1 1456812960
现在,我正在尝试根据 event_time 为用户定义一个 'session_id'。如果事件在 180 秒的滞后后出现,则事件被视为来自新会话。所以,我想要类似于以下的输出:
user_id event_time session_id
1 1456812346 1
1 1456812350 1
1 1456812446 1
1 1456812950 2
1 1456812960 2
会话在第 4 行递增,因为第 3 行之后的时间是 504 秒,因此超过了 180 秒的阈值。
在Mysql中,我可以只声明一个变量然后有条件地递增它。由于 BigQuery 不支持创建变量,是否有其他方法可以实现此目的?
SELECT
user_id, event_time, session_id
FROM (
SELECT
user_id, event_time, event_time - last_time > 180 AS new_session,
SUM(IFNULL(new_session, 1))
OVER(PARTITION BY user_id ORDER BY event_time) AS session_id
FROM (
SELECT user_id, event_time,
LAG(event_time) OVER(PARTITION BY user_id ORDER BY event_time) AS last_time
FROM YourTable
)
)
ORDER BY event_time