Count number of rows that are not within 10 seconds of each other

后端 未结 8 622
情歌与酒
情歌与酒 2021-02-01 09:26

I track web visitors. I store the IP address as well as the timestamp of the visit.

ip_address    time_stamp
180.2.79.3  1301654105
180.2.79.3  1301654106
180.2.         


        
8条回答
  •  一个人的身影
    2021-02-01 09:46

    For giggles sakes, here is an UPDATE hack that accomplishes what you need. There are a myriad of reasons not to implement this, including but not limited to the fact that it may simply stop working some day. Anyway, assuming you have your table initially ordered by ip -> timestamp, this should (usually) give you the correct answers. Again, this is for completeness, if you implement this, look up the risks beforehand.

    CREATE TABLE #TestIPs
    (
        ip_address varchar(max),
        time_stamp decimal(12,0),
        cnt int
        )
    
    INSERT INTO #TestIPs (ip_address, time_stamp)
    SELECT '180.2.79.3',  1301654105 UNION ALL
    SELECT '180.2.79.3',  1301654106 UNION ALL
    SELECT '180.2.79.3',  1301654354 UNION ALL
    SELECT '180.2.79.3',  1301654356 UNION ALL
    SELECT '180.2.79.3',  1301654358 UNION ALL
    SELECT '180.2.79.3',  1301654366 UNION ALL
    SELECT '180.2.79.3',  1301654368 UNION ALL
    SELECT '180.2.79.3',  1301654422 UNION ALL
    SELECT '180.2.79.4',  1301654105 UNION ALL
    SELECT '180.2.79.4',  1301654106 UNION ALL
    SELECT '180.2.79.4',  1301654354 UNION ALL
    SELECT '180.2.79.4',  1301654356 UNION ALL
    SELECT '180.2.79.4',  1301654358 UNION ALL
    SELECT '180.2.79.4',  1301654366 UNION ALL
    SELECT '180.2.79.4',  1301654368 UNION ALL
    SELECT '180.2.79.4',  1301654422
    
    DECLARE @count int; SET @count = 0
    DECLARE @ip varchar(max); SET @ip = 'z'
    DECLARE @timestamp decimal(12,0); SET @timestamp = 0;
    
    UPDATE #TestIPs
        SET @count = cnt = CASE WHEN time_stamp - @timestamp > 10 THEN @count + 1 ELSE CASE WHEN @ip <> ip_address THEN 1 ELSE @count END END,      
            @timestamp = time_stamp,
            @ip = ip_address
    
    
            SELECT ip_address, MAX(cnt) AS 'Visits' FROM #TestIPs GROUP BY ip_address
    

    Results:

    ip_address  Visits
    ------------ -----------
    180.2.79.3  3
    180.2.79.4  3
    

提交回复
热议问题