SQL-01求连续七天登陆的用户

发布时间:2024年01月18日

数据准备

CREATE TABLE `user_login` (
  `id` int NOT NULL AUTO_INCREMENT,
  `user_id` int DEFAULT NULL,
  `login_date` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci

#插入数据
INSERT INTO study.user_login (user_id,login_date) VALUES 
(100,'2023-10-01 00:00:00.0')
,(100,'2023-10-02 00:00:00.0')
,(100,'2023-10-03 00:00:00.0')
,(100,'2023-10-04 00:00:00.0')
,(100,'2023-10-05 00:00:00.0')
,(100,'2023-10-06 00:00:00.0')
,(100,'2023-10-07 00:00:00.0')
,(100,'2023-10-07 00:00:00.0')
,(200,'2023-10-20 00:00:00.0')
,(200,'2023-10-22 00:00:00.0')
;
INSERT INTO study.user_login (user_id,login_date) VALUES 
(200,'2023-10-23 00:00:00.0')
;

SQL

select 
	log_date,
	user_id from 
(
	select 
		*,
		date_sub(log_date,interval rank_num day) real_date
	from 
		(
				select 
					*,
					row_number() over (partition by user_id order by log_date ) as rank_num
				from  
				(
					select 
						distinct date(login_date) as log_date ,user_id
					from study.user_login 
				 ) a
		) b
) c
group by real_date, user_id HAVING COUNT(*) >=7 




请自行观察结果

文章来源:https://blog.csdn.net/qq_36066039/article/details/135645637
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。