话不多说, 先看数据表信息.
数据表如图:
有用户表行为记录表t_act_records表,包含两个字段:uid(用户ID),imp_date(日期)
话不多说, 再看需求~
编写一个 sql 查询,计算2021年每个月,每个用户连续登录的最多天数?
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天都有登录的用户名单?
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天都有登录的用户数?
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;
最后给大家介绍一下我这边的创建数据表和插入数据的操作步骤, 想要自己测试的话, 可以参考:
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);