我有一个如下所示的数据集:
{{1}}
我想计算每个user_id从数据集中最早的day_session开始的连续日会话数。因此用户xyz789将返回1,abc123将返回14并且def456将返回38. TIA
答案 0 :(得分:1)
根据您的数据,您可以这样做:
select t.user, count(*)
from t left join
(select user, min(day_session) as minds
from t
where day_diff > 1
group by user
) tt
on t.user = tt.user
where tt.minds is null or t.day_session < tt.minds
group by t.user;
答案 1 :(得分:0)
对于它的价值,这是一个使用SQL Server的解决方案:
declare @order table (rowid int identity, user_id varchar(max), day_session datetime, isconsecutive int)
insert @order
select distinct user_id, day_session,
case
when
lag(user_id, 1,0) over (order by user_id desc, day_session)=user_id and
lag(day_session, 1,0) over
(order by user_id desc, day_session)=dateadd(dd,-1,day_session)
then 1
else 0
end
from #temp
order by user_id desc, day_session
declare @holding table (user_id varchar(max), consday int, day_session datetime)
declare @iterator int=1
declare @userid varchar(max)
declare @userid2 varchar(max)
declare @isconsecutive int=1
while @iterator<=(select max(rowid) from @order)
begin
select @userid=user_id, @isconsecutive=isconsecutive
from @order
where rowid=@iterator
if @isconsecutive=0 and
(select user_id from @order where rowid=@iterator-1)=
(select user_id from @order where rowid=@iterator)
select @userid2=@userid+'_'+cast(@iterator as varchar)
if (select user_id from @order where rowid=@iterator-1)<>(select user_id from @order where rowid=@iterator)
select @userid2=null
insert @holding
select isnull(@userid2, @userid) , isconsecutive, day_session
from @order
where rowid=@iterator
set @iterator=@iterator+1
end
select user_id, max(cnt) maxconsdays from(
select substring(user_id, 1, len(user_id)-charindex('_', reverse(user_id)))user_id, sum(consday)+1 cnt from @holding
group by user_id)a
group by user_id
order by user_id desc