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

Untitled

By: a guest on May 8th, 2012  |  syntax: None  |  size: 2.02 KB  |  hits: 9  |  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. Matching user actions from a MySQL table: each CLOSE should match the previous OPEN for a given user
  2. TABLE USER_ACTIONS
  3. ------------------------
  4. USER | TYPE  | TIMESTAMP
  5. ------------------------
  6. a    | OPEN  | 0
  7. b    | OPEN  | 1
  8. a    | CLOSE | 2
  9. a    | OPEN  | 3
  10. b    | CLOSE | 4
  11. a    | CLOSE | 4
  12. a    | OPEN  | 5  <-- "orphaned" OPEN, with no corresponding CLOSE. Should be ignored.
  13. c    | OPEN  | 3
  14. c    | CLOSE | 5
  15. a    | OPEN  | 6
  16. a    | CLOSE | 8
  17.        
  18. USER | TRANSACTION_TIME
  19. -----------------------
  20. a    | 2
  21. b    | 3
  22. a    | 1
  23. c    | 2
  24. a    | 2
  25.        
  26. for each CLOSE_ACTION IN ("SELECT USER, TYPE, TIMESTAMP FROM USER_ACTIONS WHERE TYPE='CLOSE' ORDER BY TIMESTAMP DESC;") {
  27.     OPEN_ACTION = "SELECT USER, TYPE, TIMESTAMP FROM USER_ACTIONS
  28.                    WHERE TYPE='OPEN'
  29.                    AND USER='<CLOSE_ACTION.USER>'
  30.                    AND TIMESTAMP='<CLOSE_ACTION.TIMESTAMP>'
  31.                    ORDER BY TIMESTAMP DESC
  32.                    LIMIT 1";
  33.     if OPEN_ACTION != empty/null then {
  34.         print CLOSE_ACTION.USER, CLOSE_ACTION.TIMESTAMP - OPEN_ACTION.TIMESTAMP;
  35.     }
  36. }
  37.        
  38. SELECT
  39.   OPEN.user,
  40.   OPEN.transaction_time
  41.   CLOSE.transaction_time
  42. FROM
  43.   user_actions as CLOSE
  44. INNER JOIN
  45.   user_actions as OPEN
  46.     ON  OPEN.user = CLOSE.user
  47.     AND OPEN.transaction_time = (SELECT MAX(transaction_time) FROM user_action
  48.                                  WHERE user = CLOSE.user
  49.                                  AND transaction_time < CLOSE.transaction_time
  50.                                  AND type='OPEN')
  51. WHERE
  52.     CLOSE.type = 'CLOSE'
  53.        
  54. select user,
  55.        timestamp,
  56.        (select min(timestamp)
  57.         from user_actions u
  58.         where a.user = u.user and
  59.               u.type = 'CLOSE' and
  60.               u.timestamp > a.timestamp) - timestamp
  61. from user_actions a
  62. where type = 'OPEN'
  63.        
  64. select u1.user_name ,u2.timestamp- max(u1.timestamp) difference
  65. from user_actions u1,user_actions u2
  66. where u1.type = 'OPEN' and
  67. u2.type = 'CLOSE' and
  68. u1.timestamp <u2.timestamp and u1.user_name = u2.user_name
  69. group by (u1.user_name , u2.timestamp);