查询返回事件之间的时差,按ID

时间:2017-07-11 19:50:34

标签: mysql

我在mysql中有以下表格,我试图在

上查询
id    |  type  |                  dt | seqid
--------------------------------------------
1001  |  login | 2017-07-11 01:52:39 | 1
1001  | change | 2017-07-11 01:53:07 | 2
1001  | logout | 2017-07-11 01:53:21 | 3
1002  |  login | 2017-07-11 14:08:20 | 1
1002  | logout | 2017-07-11 14:08:28 | 2
--------------------------------------------

我基本上需要显示基于id分组的每个事件(类型)之间的时差。输出应该是

的内容
1001 | Login | 0   (0 calculated since login is the starting event)
1001 | change | 28 (difference between login and this event)
---------------------

等等。

我写了以下查询

SELECT 
    curr.id, 
    curr.type, 
    TIMESTAMPDIFF(SECOND,curr.dt , prev.dt) as diff 
FROM 
    sys.rep AS curr 
LEFT JOIN sys.rep AS prev ON prev.seqid = (
    SELECT min(seqid) 
    FROM sys.rep WHERE  seqid > curr.seqid and id = curr.id
);

查询适用于一个id,但多个ID失败。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

E.g。

SELECT a.*
     , timediff(b.dt,a.dt) diff
  FROM 
     ( SELECT x.*
            , MIN(y.dt) next
         FROM my_table x
         JOIN my_table y
           ON y.id = x.id
          AND y.dt > x.dt
        GROUP
           BY x.id
     ) a
  JOIN my_table b
    ON b.id = a.id
   AND b.dt = a.next;