根据状态和计算持续时间选择1条记录并循环sql

时间:2017-02-20 10:24:26

标签: mysql

我有一张表格,其中包含以下样本记录。

Id | tutorid | status | timestamp
1  | 21      | online | '2017-01-01 12:30:20'
2  | 21      | away   | '2017-01-01 13:27:20'
3  | 31      | online | '2017-01-01 14:38:20'
4  | 21      | offline| '2017-01-01 15:30:20'
5  | 31      | away   | '2017-01-01 17:20:20'
6  | 21      | online | '2017-01-01 18:30:20'
7  | 31      | online | '2017-01-01 18:30:20'
8  | 31      | away   | '2017-01-01 19:30:20'
9  | 21      | online | '2017-01-01 19:47:20'
10 | 31      | offline| '2017-01-01 19:59:20'
11 | 21      | offline| '2017-01-01 20:01:20'

让我知道如何从在线'中选择时间戳。离线'离线'为每个tutorid。在线是日志记录和在线时间(在离线状态之前状态将更多),离线是注销时间。离开是导师的内部状态。

输出应该像

Tutorid | Online               | Offline
21      |'2017-01-01 12:30:20' | '2017-01-01 15:30:20'
31      |'2017-01-01 14:38:20' | '2017-01-01 19:59:20'
21      |'2017-01-01 18:30:20' | '2017-01-01 20:01:20'

1 个答案:

答案 0 :(得分:0)

这可能不完整,但这里是首发......

SELECT tutorid
     , MIN(n.timestamp) online
     , y_timestamp offline 
  FROM 
     ( SELECT x.*
            , MIN(y.timestamp) y_timestamp 
         FROM my_table x 
         JOIN my_table y 
           ON y.tutorid = x.tutorid 
          AND y.timestamp > x.timestamp 
          AND y.status = 'offline' 
        WHERE x.status = 'online'  
        GROUP 
           BY tutorid
            , id
     ) n 
 GROUP
    BY tutorid
     , y_timestamp 
 ORDER 
    BY online;