[SQL智慧航行者] - 连续登录

话不多说, 先看数据表信息.

数据表信息:

数据表如图:

有用户表行为记录表t_act_records表,包含两个字段:uid(用户ID),imp_date(日期)

话不多说, 再看需求~

需求:

编写一个 sql 查询,计算2021年每个月,每个用户连续登录的最多天数?

sql 复制代码
select 
    uid, 
    date_format(imp_date, '%y-%m') as month,
    max(consecutive_days) as max_consecutive_days
from (
    select 
        uid,
        imp_date,
        row_number() over (partition by uid, date_format(imp_date, '%y-%m') order by imp_date) -
        row_number() over (partition by uid, date_format(imp_date, '%y-%m') order by imp_date) as consecutive_days
    from t_act_records
    where year(imp_date) = 2021
) as subquery
group by uid, month;

编写一个 sql 查询,计算2021年每个月,连续2天都有登录的用户名单?

sql 复制代码
select distinct uid, date_format(imp_date, '%y-%m') as month
from t_act_records
where year(imp_date) = 2021
group by uid, date_format(imp_date, '%y-%m')
having count(distinct imp_date) >= 2;

编写一个 sql 查询,计算2021年每个月,连续5天都有登录的用户数?

sql 复制代码
select
    date_format(imp_date, '%y-%m') as month,
    count(distinct uid) as user_count
from (
    select
        uid,
        imp_date,
        row_number() over (partition by uid, date_format(imp_date, '%y-%m') order by imp_date) -
        row_number() over (partition by uid, date_format(imp_date, '%y-%m') order by imp_date) as consecutive_days
    from t_act_records
    where year(imp_date) = 2021
) as subquery
where consecutive_days <= 5
group by month;

最后给大家介绍一下我这边的创建数据表和插入数据的操作步骤, 想要自己测试的话, 可以参考:

sql 复制代码
DROP TABLE if EXISTS t_act_records;
CREATE TABLE t_act_records
(uid  VARCHAR(20),
imp_date DATE);

INSERT INTO t_act_records VALUES('u1001', 20210101);
INSERT INTO t_act_records VALUES('u1002', 20210101);
INSERT INTO t_act_records VALUES('u1003', 20210101);
INSERT INTO t_act_records VALUES('u1003', 20210102);
INSERT INTO t_act_records VALUES('u1004', 20210101);
INSERT INTO t_act_records VALUES('u1004', 20210102);
INSERT INTO t_act_records VALUES('u1004', 20210103);
INSERT INTO t_act_records VALUES('u1004', 20210104);
INSERT INTO t_act_records VALUES('u1004', 20210105);
相关推荐
FoldWinCard1 小时前
D5 Linux 网络及端口命令
linux·运维·服务器
聆听。。花开雨落1 小时前
mybatis的typeHandler 作用
数据库·mybatis
pxzsky2 小时前
PG17数据库安装中分分词插件:pg_jieba
数据库·postgresql·pg_jieba
kirs_ur2 小时前
SSD 在 AI 训练中的角色
大数据·服务器·人工智能
她说可以呀3 小时前
Redis哨兵
数据库·redis·bootstrap
tedcloud1233 小时前
OmniRoute怎么部署?开源AI模型路由平台Linux部署教程
linux·服务器·人工智能·开源·音视频
霸道流氓气质3 小时前
KMS 密钥管理服务(Key Management Service)原理与实践
linux·服务器·数据库
kirs_ur3 小时前
CXL(Compute Express Link)— 内存扩展的未来
服务器·数据库·性能优化
代码村新手4 小时前
Linux的基本指令
linux·运维·服务器
RestCloud4 小时前
Informatica迁移国产ETL完整实施指南:ETLCloud自动化平滑替换方案
数据仓库·etl·etlcloud·数据传输·数据集成工具·informatica·国产化替代