条件行到单行mysql

时间:2017-06-14 11:49:05

标签: mysql

表1:

    event               | time                       |id          | user 
    ---------------------------------------------------------------------
    ADDMEMBER           | 2017-06-14 08:03:58.872908 | 2335797    | x    
    REMOVEMEMBER        | 2017-06-14 09:17:02.719318 | 2337422    | x  
    ADDMEMBER           | 2017-06-14 09:28:23.343281 | 2337737    | x  
    REMOVEMEMBER        | 2017-06-14 09:46:50.189582 | 2338117    | x  

我想要的输出是每组ADDMEMBER和REMOVEMBER:

    event               | Login                      | Logoff                     |user 
    ---------------------------------------------------------------------------------------
    ADDMEMBER           | 2017-06-14 08:03:58.872908 | 2017-06-14 09:17:02.719318 | x    
    ADDMEMBER           | 2017-06-14 09:28:23.343281 | 2017-06-14 09:46:50.189582 | x    

我不知道如何做到这一点。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

假设ADDMEMBERREMOVEMEMBER事件总是配对,那么您可以使用以下查询获取LoginLogoff次:

SELECT 'ADDMEMBER', 
       MIN(`time`) AS Login,
       MAX(`time`) AS Logoff,
       user
FROM (             
   SELECT event, `time`, id, user,
          @grp := IF(event = 'ADDMEMBER', @grp + 1, @grp) AS grp                  
   FROM mytable
   CROSS JOIN (SELECT @grp := 0) AS v
   ORDER BY `user`, `time`) AS t
GROUP BY user, grp;  

Demo here