SQL 计算最长连续登录天数


参考:https://blog.csdn.net/ganghaodream/article/details/100083543

SQL计算最长登录天数

计算最长登陆天数主要用两个函数:1.窗口函数row_number()over() 2.date_sub()

1.使用row_number()窗口函数

select UID,loadtime,row_number()over(partition by UID order by loadtime) sort
from user_login

2.使用date_sub()函数

select UID,date_sub(loadtime,sort) as date_group,min(loadtime) as start, max(loadtime) as end ,count(1) as continue_days
      (select UID,loadtime,row_number()over(partition by UID order 	  by loadtime) sort
       from user_login
      ) a
group by UID,date_sub(loadtime,sort)

3.以UID分组,取max(continue_days)

select UID,max(continue_days) as maxday
      (select UID,date_sub(loadtime,sort) as 	 date_group,min(loadtime) as start, max(loadtime) as end ,count(1) as continue_days
            (select UID,loadtime,row_number()over(partition by UID order by loadtime) sort
	     from user_login
    	    ) a
       group by UID,date_sub(loadtime,sort)
      ) b
group by UID


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM