SQL to determine minimum sequential days of access?

前端 未结 19 1744
我在风中等你
我在风中等你 2020-12-04 04:58

The following User History table contains one record for every day a given user has accessed a website (in a 24 hour UTC period). It has many thousands of r

19条回答
  •  时光说笑
    2020-12-04 05:28

    You could use a recursive CTE (SQL Server 2005+):

    WITH recur_date AS (
            SELECT t.userid,
                   t.creationDate,
                   DATEADD(day, 1, t.created) 'nextDay',
                   1 'level' 
              FROM TABLE t
             UNION ALL
            SELECT t.userid,
                   t.creationDate,
                   DATEADD(day, 1, t.created) 'nextDay',
                   rd.level + 1 'level'
              FROM TABLE t
              JOIN recur_date rd on t.creationDate = rd.nextDay AND t.userid = rd.userid)
       SELECT t.*
        FROM recur_date t
       WHERE t.level = @numDays
    ORDER BY t.userid
    

提交回复
热议问题