作者SQL入门小白,此栏仅是记录一些解题过程
1、题目
用户访问表users,记录了用户id(usr_id)和访问日期(log_date),求出连续3天以上访问的用户id。
2、解答过程
2.1数据准备
通过navicat创建数据,首先创建表,设置字段类型,
然后打开数据表添加数据
2.2 解题
首先按照用户id给log_data排序
SELECT usr_id,log_data,
ROW_NUMBER() OVER (PARTITION BY usr_id
ORDER BY log_data) AS rank_id
FROM q1
得到结果 rank_id
得到排名后,我们用访问日期减去排名,得到一个时间flg_date 。
SELECT usr_id,
DATE_SUB(log_date,INTERVAL rank_id DAY) AS flg_date
FROM (
SELECT usr_id, log_date,
ROW_NUMBER() OVER (PARTITION BY usr_id ORDER BY log_date) AS rank_id
FROM users
) AS A
同一个用户有3个及以上flg_date相同,说明用户连续访问3天。
SELECT
usr_id,
DATE_SUB(log_date,INTERVAL rank_id DAY) AS flg_date
FROM (
SELECT
usr_id,
log_date,
ROW_NUMBER() OVER (PARTITION BY usr_id ORDER BY log_date) AS rank_id
FROM users
) AS A
GROUP BY usr_id,flg_date
HAVING COUNT(flg_date) >=3