Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 6th, 2012  |  syntax: None  |  size: 1.07 KB  |  hits: 12  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. How to calculate an SQL MAX() for any N-second duration within a certain timeframe
  2. -- Timestamped log of users viewing items
  3. CREATE TABLE user_item_views (
  4.   user_id integer,
  5.   item_id integer,
  6.   timestamp timestamp
  7. );
  8.        
  9. User ID  Max items viewed in N seconds, between START and END.
  10. ...      ...
  11. ...      ...
  12. ...      ...
  13.        
  14. SELECT
  15.   s.timestamp,
  16.   v.user_id,
  17.   (
  18.    SELECT COUNT(*) FROM user_item_views
  19.     WHERE timestamp BETWEEN s.timestamp AND ADDTIME(s.timestamp, '00:00:59')
  20.           AND user_id = v.user_id
  21.   ) item_count
  22. FROM
  23.   every_second s
  24.   LEFT JOIN user_item_views v ON v.timestamp = s.timestamp
  25. GROUP BY
  26.   s.timestamp,
  27.   v.user_id
  28.        
  29. SELECT
  30.       user_id
  31.     , MAX(max_count) AS max_count
  32. FROM
  33.   ( SELECT
  34.           a.user_id
  35.         , COUNT(*)      AS max_count
  36.     FROM
  37.           user_item_views AS a
  38.       JOIN
  39.           user_item_views AS b
  40.         ON  a.user_id = b.user_id
  41.         AND a.timestamp <= b.timestamp
  42.         AND b.timestamp < a.timestamp + INTERVAL 60 SECOND
  43.     GROUP BY
  44.           a.user_id
  45.         , a.timestamp
  46.   ) AS grp
  47. GROUP BY
  48.       user_id