当前位置:网站首页>SQL interview question: find the maximum number of consecutive login days

SQL interview question: find the maximum number of consecutive login days

2022-06-28 19:02:00 South Lake Fishing Song

Find the maximum number of continuous login days for users mysql Realization
 Insert picture description here

with t_1 as( --  Use timestampdiff(unit, begin, end) <= 30 Conduct where Conditional filtering , And use distinct Function to get a new table t_1
select DISTINCT  dimMemberID as user_id, date(dimDateID) as login_date
from fct_sales
where timestampdiff(day, date(dimDateID),(select max(dimDateID) from fct_sales)) <=  30
      and  dimMemberID <> 0
order by login_date
),t_2 as( --  Get a press user_id A new table grouped with a sort number t_2
select  user_id
       ,login_date
       ,row_number()over(partition by user_id order by login_date asc ) as ranks
from t_1
),t_3 as ( --  Use date_sub Function to get a new column gap And new tables t_3
select   user_id 
		,login_date
		,ranks
		,date_sub(login_date, interval ranks day) as gap
from t_2
),  t_4 as ( --  Yes t_3 Table by user_id、gap Grouping , And for the login_date Conduct count Count , Get the table t_4
select  user_id
       ,gap
       ,count(login_date) as num
from t_3
group by  user_id
         ,gap
) ,t_5 as ( --  according to user_id Grouping , Use max Take out the biggest num
select  user_id
       ,max(num) as series_login --  according to user_id grouping , Find the maximum number of consecutive login days 
from t_4 
group by user_id
)
select * ,count(1)over() as cnt  from t_5;
  • with t_1 as
  • timestampdiff

Reference resources

原网站

版权声明
本文为[South Lake Fishing Song]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/179/202206281837393957.html