创建表格
create table 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 )
思路
将表按照id分组根据时间排名,时间减去排名rnk,如果时间是连续的则相减的结果相等:
select *,date-排名 rnk from (select *,row_number() over(partition by id order by date) 排名 from orde) a;
然后按照id,rnk分组,计数
select id,rnk,count(*) ok from (select *,date-排名 rnk from (select *,row_number() over(partition by id order by date) 排名 from orde) a) b group by id,rnk;
得到下表:
最后筛选计数项ok>=7的。
还可以直接进行筛选:
select id,rnk from (select *,date-排名 rnk from (select *,row_number() over(partition by id order by date) 排名 from orde) a) b group by id,rnk having count(*)>=7;
以上所述是www.887551.com给大家介绍的sql查询至少连续七天下单的用户,希望对大家有所帮助。在此也非常感谢大家对www.887551.com网站的支持!