SQL to determine minimum sequential days of access?

前端 未结 19 1743
我在风中等你
我在风中等你 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:29

    The answer is obviously:

    SELECT DISTINCT UserId
    FROM UserHistory uh1
    WHERE (
           SELECT COUNT(*) 
           FROM UserHistory uh2 
           WHERE uh2.CreationDate 
           BETWEEN uh1.CreationDate AND DATEADD(d, @days, uh1.CreationDate)
          ) = @days OR UserId = 52551
    

    EDIT:

    Okay here's my serious answer:

    DECLARE @days int
    DECLARE @seconds bigint
    SET @days = 30
    SET @seconds = (@days * 24 * 60 * 60) - 1
    SELECT DISTINCT UserId
    FROM (
        SELECT uh1.UserId, Count(uh1.Id) as Conseq
        FROM UserHistory uh1
        INNER JOIN UserHistory uh2 ON uh2.CreationDate 
            BETWEEN uh1.CreationDate AND 
                DATEADD(s, @seconds, DATEADD(dd, DATEDIFF(dd, 0, uh1.CreationDate), 0))
            AND uh1.UserId = uh2.UserId
        GROUP BY uh1.Id, uh1.UserId
        ) as Tbl
    WHERE Conseq >= @days
    

    EDIT:

    [Jeff Atwood] This is a great fast solution and deserves to be accepted, but Rob Farley's solution is also excellent and arguably even faster (!). Please check it out too!

提交回复
热议问题