SQL面试题挑战11:访问会话切割

目录

问题:

如下为某电商公司用户访问网站的数据,包括用户id和访问时间两个字段。现有如下规则:如果某个用户的连续的访问记录时间间隔小于60秒,则属于同一个会话,现在需要计算每个用户有多少个会话。比如A用户在第1秒,60秒,200秒,230秒有三次访问记录,则该用户有2个会话,其中第一个会话是第1秒和第60秒的记录,第二个会话是第200秒和230秒的记录。

powershell 复制代码
user_id     ts
1001    16920000000
1001    16920000050
1002    16920000065
1002    16920000080
1001    16920000150
1002    16920000160

SQL解答:

先按用户分组、时间排序后取每行数据的前一行的时间,然后判断当前行的时间与前一行时间的差值,看是否在给定的范围内,然后再做开窗累加就可以得到每个用户不同的会话编号了。思路如下图:

user_id ts 判断与上一行差值是否小于60 开窗累加当做会话编号
A 1 0 0
A 60 0 0
A 200 1 1
A 230 0 1
sql 复制代码
with tmp as (
    select 1001 as user_id,16920000000 as ts
    union all
    select 1001 as user_id,16920000050 as ts
    union all
    select 1002 as user_id,16920000065 as ts
    union all
    select 1002 as user_id,16920000080 as ts
    union all
    select 1001 as user_id,16920000150 as ts
    union all
    select 1002 as user_id,16920000160 as ts
)
 
select
	user_id
	,count(distinct user_group) as user_group_cnt
from
(
 select
    user_id
    ,ts
    -- 开窗做累加
    ,sum(flag) over(partition by user_id order by ts) as user_group
    from
    (
select
        user_id
        ,ts
        -- 判断当前行的时间与上一行的差值
        ,if(ts-last_ts<60,0,1) as flag
        from
        (
select
 user_id
 ,ts
 -- 取当前行的上一个时间,没有上一行就给自身的时间
 ,lag(ts,1,ts) over(partition by user_id order by ts) as last_ts
 from tmp
)t1
)t1
)t1
group by user_id;
相关推荐
-SGlow-6 小时前
MySQL相关概念和易错知识点(2)(表结构的操作、数据类型、约束)
linux·运维·服务器·数据库·mysql
明月5667 小时前
Oracle 误删数据恢复
数据库·oracle
♡喜欢做梦8 小时前
【MySQL】深入浅出事务:保证数据一致性的核心武器
数据库·mysql
遇见你的雩风8 小时前
MySQL的认识与基本操作
数据库·mysql
dblens 数据库管理和开发工具8 小时前
MySQL新增字段DDL:锁表全解析、避坑指南与实战案例
数据库·mysql·dblens·dblens mysql·数据库连接管理
weixin_419658318 小时前
MySQL的基础操作
数据库·mysql
不辉放弃9 小时前
ZooKeeper 是什么?
数据库·大数据开发
Goona_10 小时前
拒绝SQL恐惧:用Python+pyqt打造任意Excel数据库查询系统
数据库·python·sql·excel·pyqt
程序员编程指南10 小时前
Qt 数据库连接池实现与管理
c语言·数据库·c++·qt·oracle
幼儿园老大*12 小时前
数据中心-时序数据库InfluxDB
数据库·时序数据库