如何在 mysql 中按状态(有人进入然后退出)对行进行配对

How to pair rows by status (someone entered and then exited) in mysql

我有一个 table user_status,我在其中插入行:who状态 (Entered/Exited),几点。 Table 看起来像这样:

id  user_id  status   status_date
94  5        Entered  2015-03-30 10:43:44
95  5        Exited   2015-03-30 10:47:38
96  5        Entered  2015-03-30 10:49:12
97  3        Entered  2015-03-30 10:51:14
98  3        Exited   2015-03-30 11:04:12
99  5        Exited   2015-03-30 11:16:50
100 3        Entered  2015-03-30 11:20:48
101 5        Entered  2015-03-30 11:21:37
102 2        Exited   2015-03-30 11:24:47
103 2        Entered  2015-03-30 11:25:01

现在我想创建一个程序,为特定用户匹配的行配对 his/her 已退出状态和 returns 临时 table。结果应该是这样的:

id  user_id  status_date_start    status_date_end
1  5         2015-03-30 10:43:44  2015-03-30 10:47:38
2  5         2015-03-30 10:49:12  2015-03-30 11:16:50
3  3         2015-03-30 10:51:14  2015-03-30 11:04:12
...

我尝试了双重内部连接,user_status 上的游标,但我没有成功。请帮忙

只是稍微尝试了一下,让它在查询中使用额外的 select。

-- set up some test data
GO 
DECLARE @moves TABLE
    (
        id INT,
        user_id INT,
        status NVARCHAR(MAX),
        status_date DATETIME
    )

INSERT INTO @moves VALUES (94, 5 , 'Entered', '2015-03-30 10:43:44')
INSERT INTO @moves VALUES (95, 5 , 'Exited', ' 2015-03-30 10:47:38')
INSERT INTO @moves VALUES (96, 5 , 'Entered', '2015-03-30 10:49:12')
INSERT INTO @moves VALUES (97, 3 , 'Entered', '2015-03-30 10:51:14')
INSERT INTO @moves VALUES (98, 3 , 'Exited', '2015-03-30 11:04:12')
INSERT INTO @moves VALUES (99, 5 , 'Exited', '2015-03-30 11:16:50')

-- original data --
SELECT * FROM @moves


-- selecting the exit date into the original data --
SELECT 
    m.id
    ,m.user_id
    ,m.status_date
    ,(
        SELECT TOP 1  status_date
        FROM @moves x 
        WHERE x.user_id = m.user_id
        AND x.status = 'Exited'
        AND x.id > m.id
    ) as 'exit'
FROM @moves m  
WHERE m.status ='Entered'

结果: