题解 | #最大连续回答问题天数大于等于3天的用户#
某乎问答最大连续回答问题天数大于等于3天的用户及其对应等级
https://www.nowcoder.com/practice/e080f8a685bc4af3b47749ca3310f1fd
with a as( -- 对于前表求计数即可得到连续天数大于3的用户了,至此,实际上本例题已完成 select author_id, author_level, count(1) day_cnt -- ,fst_dt from ( -- 求连续期间天数,实际上就是求:同一起始日期,活跃/回答的日期(去重计数) -- 利用去重取巧,保留同一用户,同一起始日期,活跃/回答的日期 -- 此处也可以使用group by实现同样的效果 select distinct author_id, date_sub(answer_date, interval dense_rank() over (partition by author_id order by answer_date) - 1 day) fst_dt, answer_date from answer_tb # 效果如下: # | author_id | fst_dt | answer_date | # | 101 | 2021-11-01 | 2021-11-01 | # | 101 | 2021-11-01 | 2021-11-02 | # | 101 | 2021-11-01 | 2021-11-03 | # | 102 | 2021-11-01 | 2021-11-01 | ) t1 left join author_tb using (author_id) group by author_id, author_level, fst_dt having day_cnt >= 3 ) -- 从上面的题解不难发现,如果遇到一个用户,有多次连续回答超过3天(如11-01到11-03和11-05到11-08都回答了) -- 那么会得到同一个用户多条记录,因为上面实际求得是:同一用户,在同一起始日期算,连续回答了多少天 -- 可以最后套一层最大值 select author_id, author_level, max(day_cnt) day_cnt from a group by author_id, author_level;