SQL to determine minimum sequential days of access?

前端 未结 19 1745
我在风中等你
我在风中等你 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-04 05:18

    Off the top of my head, MySQLish:

    SELECT start.UserId
    FROM UserHistory AS start
      LEFT OUTER JOIN UserHistory AS pre_start ON pre_start.UserId=start.UserId
        AND DATE(pre_start.CreationDate)=DATE_SUB(DATE(start.CreationDate), INTERVAL 1 DAY)
      LEFT OUTER JOIN UserHistory AS subsequent ON subsequent.UserId=start.UserId
        AND DATE(subsequent.CreationDate)<=DATE_ADD(DATE(start.CreationDate), INTERVAL 30 DAY)
    WHERE pre_start.Id IS NULL
    GROUP BY start.Id
    HAVING COUNT(subsequent.Id)=30
    

    Untested, and almost certainly needs some conversion for MSSQL, but I think that give some ideas.

提交回复
热议问题