参考该博客 https://bbs.csdn.net/topics/392243867
数据为:用户id#uid 登录日期#loaddate
uid loaddate
201 2017-01-06 00:00:00
201 2017-01-05 00:00:00
201 2017-01-04 00:00:00
201 2017-01-01 00:00:00
201 2017-01-02 00:00:00
202 2017-01-03 00:00:00
202 2017-01-05 00:00:00
202 2017-01-02 00:00:00
202 2017-01-04 00:00:00
203 2017-01-03 00:00:00
203 2017-01-06 00:00:00
203 2017-01-07 00:00:00
sql为
Select uid,max(cnt) as cnt
From (Select uid,Grp_No,count(*) as cntFrom (Select uid,loaddate,date_sub(loaddate,ROW_NUMBER() OVER (Partition By uid Order By uid,loaddate)) as Grp_No From t_lastmaxnum_dd) aGroup By uid,Grp_No) a
Group By uid;
简单解释下这段sql,重点当然是 这里
date_sub(loaddate,ROW_NUMBER() OVER (Partition By uid Order By uid,loaddate))
单独运行这段的结果为
功能就是:连续的日期得到的grp_no都是相同的,得到这个之后再进行group by就可以得到最大的连续天数了,还是很秀的一段sql
注意:源博客里用的DAY是有问题的,这样在月份差异下可能造成仍被认为是连续的! 比如uid=206 loaddata=2017-06-04这条数据会被认为和2017-05-03是连续的