SQL查询找到每个用户的activity时间

SQL Query to find the activity time of each user

我们如何使用这些数据来计算每个用户在每个时期的activity?

user_id       date            status 
 101        2018-01-1          1 
 101        2018-01-2          0 
 101        2018-01-3          1   
 101        2018-01-4          1 
 101        2018-01-5          1

输出:

 user_id  start_date     end_date  status  length 
   101    2018-01-1    2018-01-1    1      1
   101    2018-01-2    2018-01-2    0      1
   101    2018-01-3    2018-01-5    1      3

这是一个 gaps-and-islands 问题。您可以通过减去一个序列将它们组合在一起:

select user_id, status, min(date), max(date),
       julianday(max(date)) - julianday(min(date)) as length
from (select t.*,
             row_number() over (partition by user_id, status order by date) as seqnum
      from t
     ) t
group by user_id, status, date(date, '-' || seqnum || ' day')
order by user_id, length;

Here 是一个 db<>fiddle.