题解 | #最长连续登录天数#
最长连续登录天数
https://www.nowcoder.com/practice/cb8bc687046e4d32ad38de62c48ad79b
/* with connect as ( select * ,lead(fdate,1)over() as fdate1 from tb_dau ) ,jug1 as (select * ,case when date_add(fdate,interval 1 day)=fdate1 then '连续_最后一天不显示' #连续的最后一天不会显示连续,所以没必要给最后一行也定连续 else '不连续' end as jug from connect ) #难点出现了,如何统计一个用户这些断开的连续区间里面的连续元素数量 #先给出结论,这类题的核心是:分组排序,用时间减去排序,如果连续的,则它们的差会是相同值。 #并且不同的断开的连续区间,差值是不同的且对应唯一一个连续区间,比如 1号和2号是连续的,这个连续区间定义为A1,差值为0.之后直接跳到10号,则10号对应序号为3,假设10号和11号是连续的,则差值为7。这样就可以根据差值进行分组。 */ with fenzupaixu as ( select * ,row_number()over(partition by user_id order by fdate asc) as t_rank from tb_dau where fdate between '2023-01-01' and '2023-02-01' ) ,chazhi as ( select * ,day(fdate)-t_rank as datedif from fenzupaixu ) ,con_days as (select user_id ,count(fdate) as con_day from chazhi group by user_id , datedif ) select user_id ,max(con_day) as max_consec_days from con_days group by user_id