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

posted @ 2020-11-06 12:25  从前有座山,山上  阅读(6537)  评论(0编辑  收藏  举报