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

后端 未结 8 698
情歌与酒
情歌与酒 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 10:03

    You could JOIN the tracking table to itself and filter out the records you don't need by adding a WHEREclause.

    SELECT  t1.ip_address
            , COUNT(*) AS tracks
    FROM    tracking t1
            LEFT OUTER JOIN tracking t2 ON t2.ip_address = t1.ip_address
                                           AND t2.time_stamp < t1.time_stamp + 10
    WHERE   t2.ip_adress IS NULL
    GROUP BY
            t1.ip_address
    

    Edit

    Following script works in SQL Server but I can't express it in a single SQL statement, let alone convert it to MySQL. It might give you some pointers on what is needed though.

    Note: I assume for given inputs, number 1 and 11 should get chosen.

    ;WITH q (number) AS (
      SELECT 1
      UNION ALL SELECT 2
      UNION ALL SELECT 10
      UNION ALL SELECT 11  
      UNION ALL SELECT 12
    )
    SELECT  q1.Number as n1
            , q2.Number as n2
            , 0 as Done
    INTO    #Temp
    FROM    q q1
            LEFT OUTER JOIN q q2 ON q2.number < q1.number + 10
                                    AND q2.number > q1.number
    
    DECLARE @n1 INTEGER
    DECLARE @n2 INTEGER
    
    WHILE EXISTS (SELECT * FROM #Temp WHERE Done = 0)
    BEGIN
    
      SELECT  TOP 1 @n1 = n1
              , @n2= n2
      FROM    #Temp
      WHERE   Done = 0
    
      DELETE  FROM #Temp
      WHERE   n1 = @n2
    
      UPDATE  #Temp 
      SET     Done = 1
      WHERE   n1 = @n1 
              AND n2 = @n2         
    END        
    
    SELECT  DISTINCT n1 
    FROM    #Temp
    
    DROP TABLE #Temp
    

提交回复
热议问题