SQL查询找到时差

时间:2015-09-24 03:24:15

标签: sql

我想找到用户登录和注销之间的时差。 对我来说困难的部分是登录和注销时间都在一列中,并且有一个“状态”列来显示它是否是登录/注销。 示例:

Timestamp             Status       UserName

2015-04-26 20:12:33   Login        Grashia

2015-04-26 23:22:13   Logout       Grashia

我如何查询? 我尝试了DATEDIFF功能,但我知道这不是正确的方法。

2 个答案:

答案 0 :(得分:1)

假设您有以下表格架构

CREATE TABLE `user_log` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) DEFAULT NULL,
  `dt` datetime DEFAULT NULL,
  `status` varchar(15) COLLATE utf8_bin DEFAULT NULL,
  PRIMARY KEY (`id`)
);

使用这种数据

+----+---------+---------------------+--------+
| id | user_id | dt                  | status |
+----+---------+---------------------+--------+
|  1 |       1 | 2015-09-23 08:35:36 | Login  |
|  2 |       1 | 2015-09-23 17:15:44 | Logout |
|  3 |       1 | 2015-09-24 08:55:18 | Login  |
|  4 |       2 | 2015-09-23 09:00:16 | Login  |
|  5 |       2 | 2015-09-23 18:00:23 | Logout |
+----+---------+---------------------+--------+

您可以使用此查询

SELECT i.user_id, i.dt AS 'login_dt', IFNULL(o.dt, '-') AS 'logout_dt',
    TIMEDIFF(IFNULL(o.dt, NOW()), i.dt) AS 'total_time' 
FROM
    (SELECT * FROM user_log WHERE `status`='Login') i
    LEFT OUTER JOIN (SELECT * FROM user_log WHERE `status`='Logout') o 
        ON i.user_id=o.user_id AND DATE(i.dt)=DATE(o.dt)

获得此结果

+---------+---------------------+---------------------+------------+
| user_id | login_dt            | logout_dt           | total_time |
+---------+---------------------+---------------------+------------+
|       1 | 2015-09-23 08:35:36 | 2015-09-23 17:15:44 | 08:40:08   |
|       1 | 2015-09-24 08:55:18 | -                   | 00:10:23   |
|       2 | 2015-09-23 09:00:16 | 2015-09-23 18:00:23 | 09:00:07   |
+---------+---------------------+---------------------+------------+

您必须添加所需的索引并设置适当的表引擎以获得最佳性能

答案 1 :(得分:1)

如果是SQL服务器,您的查询将如下所示:

我想应该有一个列userid:

您需要连接两个表以在同一列中进行比较数据

SELECT in. username, DATEDIFF(minute, in.timestamp, out.timestamp)
FROM
(SELECT username, timestamp FROM logtable WHERE status = 'Login') as IN
INNER JOIN
(SELECT username, timestamp FROM logtable WHERE status = 'logout') AS OUT 
ON in.userid =  out.useriD

您可以在此处阅读有关DATEDIFF功能的更多信息:

  

https://msdn.microsoft.com/en-us/library/ms189794.aspx