思路分析:
(1)为每一次浏览找到他的上一次浏览时间
lag(view_timestamp, 1, 0) over(partition by user_id order by view_timestamp) as last_view_timestamp
(2)为>60s的设置一个初始会话的标签flagif(view_timestamp - last_view_timestamp > 60, 1, 0) flag
(3)对flag开窗求和,属于同一会话的和相同。sum(flag) over(PARTITION by user_id ORDER by view_timestamp) flag
(4)使用user_id与flag拼接会话id,结果就是相邻两次会话间隔不超过60s的id相同。
注:lag(view_timestamp, 1, 0) 表示向上取一行,取不到的赋默认值0
这道题将会话划分问题转化为flag的打标问题,同一会话内flag求和相同
代码实现:
select
user_id,
page_id,
view_timestamp,
concat(user_id, '-', flag) session_id
from(
SELECT
user_id,
page_id,
view_timestamp,
sum(flag) over(PARTITION by user_id ORDER by view_timestamp) flag
from(
SELECT
user_id,
page_id,
view_timestamp,
--为>60s的设置一个初始会话的标签
if(view_timestamp - last_view_timestamp > 60, 1, 0) flag
from(
SELECT
user_id,
page_id,
view_timestamp,
--0表示取不到时候赋予的默认值
lag(view_timestamp, 1, 0) over(partition by user_id order by view_timestamp) as last_view_timestamp
from page_view_events
) t1
) t2
) t3;