SQL 查詢連續登錄的用戶情況

以連續3天為例,使用工具:MySQL。

1.創建SQL表:

create table if not exists orde(id varchar(10),date datetime,orders varchar(10));
insert into orde values('1' , '2019/1/1',10 );
insert into orde values('1' , '2019/1/2',109 );
insert into orde values('1' , '2019/1/3',150 );
insert into orde values('1' , '2019/1/4',99);
insert into orde values('1' , '2019/1/5',145);
insert into orde values('1' , '2019/1/6',1455);
insert into orde values('1' , '2019/1/7',199);
insert into orde values('1' , '2019/1/8',188 );
insert into orde values('4' , '2019/1/1',10 );
insert into orde values('2' , '2019/1/2',109 );
insert into orde values('3' , '2019/1/3',150 );
insert into orde values('4' , '2019/1/4',99);
insert into orde values('5' , '2019/1/5',145);
insert into orde values('6' , '2019/1/6',1455);
insert into orde values('7' , '2019/1/7',199);
insert into orde values('8' , '2019/1/8',188 );
insert into orde values('9' , '2019/1/1',10 );
insert into orde values('9' , '2019/1/2',109 );
insert into orde values('9' , '2019/1/3',150 );
insert into orde values('9' , '2019/1/4',99);
insert into orde values('9' , '2019/1/6',145);
insert into orde values('9' , '2019/1/9',1455);
insert into orde values('9' , '2019/1/10',199);
insert into orde values('9' , '2019/1/13',188 );

查看數據表:

2.使用row_number() over()  排序函數計算每個id的排名,SQL如下:

select *,row_number() over(partition by id order by date ) 'rank'
from orde
where orders is not NULL;

查看數據表:

 3.將date日期字段減去rank排名字段,SQL如下:

select *,DATE_SUB(a.date,interval a.rank day) 'date_sub'
from(
select *,row_number() over(partition by id order by date ) 'rank'
from orde
where orders is not NULL
) a;

查看數據:

 

4.根據id和date分組並計算分組後的數量(count)、計算最早登錄和最晚登錄的時間,SQL如下:

select b.id,min(date) 'start_time',max(date) 'end_time',count(*) 'date_count'
from(
select *,DATE_SUB(a.date,interval a.rank day) 'date_sub'
from(
select *,row_number() over(partition by id order by date ) 'rank'
from orde
where orders is not NULL
) a
) b
group by b.date_sub,id
having count(*) >= 3
;

 查看數據:

參考資料: 

(28條消息) SQL查詢連續七天以上下單的用戶_方便面袋袋的博客-CSDN博客_統計連續七天都有下單的

https://blog.csdn.net/qq_43807789/article/details/99091753?spm=1001.2101.3001.6661.1&utm_medium=distribute.pc_relevant_t0.none-task-blog-2~default~CTRLIST~default-1.highlightwordscore&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-2~default~CTRLIST~default-1.highlightwordscore

到此這篇關於SQL 查詢連續n天登錄的用戶情況的文章就介紹到這瞭,更多相關SQL 查詢用戶連續登錄情況內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: