连续登录2-7天用户
建表
create table continuous_login( user_id1 integer comment '用户id' , date_login date comment '登陆日期'
) comment '用户登录表' ; insert into continuous_login
values ( 1 , '2022-01-10' ) , ( 1 , '2022-01-11' ) , ( 1 , '2022-01-13' ) , ( 1 , '2022-01-14' ) , ( 1 , '2022-01-15' ) , ( 1 , '2022-01-16' ) , ( 1 , '2022-01-17' ) , ( 1 , '2022-01-18' ) , ( 1 , '2022-01-19' ) , ( 2 , '2022-01-05' ) , ( 2 , '2022-01-06' ) , ( 2 , '2022-01-07' ) , ( 2 , '2022-01-11' ) , ( 3 , '2022-01-01' ) , ( 3 , '2022-01-03' ) , ( 3 , '2022-01-11' ) ;
排名找规律
with tmp as ( select * from continuous_logingroup by user_id1, date_login
) , tmp1 as ( select * , dense_rank( ) over ( partition by user_id1 order by date_login) drfrom continuous_login ) , tmp2 as ( select user_id1, count ( 1 ) days_login_consecutive, concat( min ( date_login) , '/' , max ( date_login) ) date_finish_begin from tmp1group by user_id1, adddate( date_login, - dr) having count ( 1 ) between 2 and 7 )
select user_id1, group_concat( days_login_consecutive) days_login_consecutive, group_concat( date_finish_begin) date_finish_begin
from tmp2
group by user_id1;
最大连胜次数
建表
create table if not exists match1( player_id integer unsigned not null default 0 comment '玩家ID' , match_day date default '1970-01-01' comment '比赛日期' , result1 varchar ( 5 ) comment '比赛结果'
) comment '玩家比赛表' ; insert into match1
value ( '1' , '2022-01-17' , 'Win' ) , ( '1' , '2022-01-18' , 'Win' ) , ( '1' , '2022-01-25' , 'Win' ) , ( '1' , '2022-01-31' , 'Draw' ) , ( '1' , '2022-02-08' , 'Win' ) , ( '2' , '2022-02-06' , 'lose' ) , ( '2' , '2022-02-08' , 'lose' ) , ( '3' , '2022-03-30' , 'Win' ) ;
只输出连胜结果
with tmp as ( select player_id, match_day, result1, if ( result1 = 'Win' , 1 , 0 ) result1_if, dense_rank( ) over ( partition by player_id order by match_day) dr, dense_rank( ) over ( partition by player_id, result1 order by match_day) dr1from match1
) , tmp1 as ( select player_id, sum ( result1_if) consecutive_countfrom tmpgroup by player_id, dr - dr1)
select player_id, 'Win' result1, max ( consecutive_count) max_consecutive_count
from tmp1
group by player_id;
输出所有连续结果
with tmp as ( select player_id, match_day, result1, dense_rank( ) over ( partition by player_id order by match_day) dr, dense_rank( ) over ( partition by player_id, result1 order by match_day) dr1from match1
)
select player_id, any_value( result1) result1, count ( result1) consecutive_count
from tmp
group by player_id, dr - dr1;