以连续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 ;
查看数据:
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
长按识别二维码并关注微信
更方便到期提醒、手机管理