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