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

标签 mysql rows procedure

我有一个表user_status,我在其中插入行:状态(进入/退出)、什么时间.表格如下所示:

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

现在我想创建一个过程,将特定用户的行与他/她的“输入”和“退出”状态相匹配,并返回临时表。结果应该是这样的:

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上,但我没有成功。请帮忙

最佳答案

只是稍微尝试了一下,让它与查询中的额外选择一起工作。

-- 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'

结果:

enter image description here

关于mysql - 如何在mysql中按状态(有人进入然后退出)对行进行配对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30591292/

相关文章:

Mysql导入远程文件到本地服务器

c++ - 在矩阵 C++ 中交换 2 行

MySQL 从外部集中选择不在表中的值

jquery - 使用 jQuery 扩展表中的某些行

mysql - 在 mysql 中,如何根据一组给定的值为表中的每一行设置一列

postgresql: "DO"处或附近的语法错误

mysql - 在 MySQL 存储函数中声明整数变量时出错

Oracle SQLDeveloper 中的 MySQL 过程

mysql - PhpMyAdmin 栏目搜索

php - 如果mysql不存在则插入值