如何查询多行的平均时差?

时间:2014-10-03 16:27:45

标签: mysql sql time average

我有下表基本上是扫描日志。

+---------------+------------------+------+-----+---------+----------------+
| Field         | Type             | Null | Key | Default | Extra          |
+---------------+------------------+------+-----+---------+----------------+
| id            | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| location_id   | int(10) unsigned | YES  | MUL | NULL    |                |
| code          | varchar(255)     | YES  |     | NULL    |                |
| created       | datetime         | YES  |     | NULL    |                |
| last_modified | datetime         | YES  |     | NULL    |                |
+---------------+------------------+------+-----+---------+----------------+

以下是一些示例数据的简单示例。 Location_id为1是enterence,location_id为2是退出。我想知道一个人(代码)从入口到出口所需的平均时间。

+----+-------------+------+---------------------+---------------+
| id | location_id | code | created             | last_modified |
+----+-------------+------+---------------------+---------------+
| 1  | 1           | 0005 | 2014-10-03 10:01:56 | NULL          |
| 2  | 1           | 0006 | 2014-10-03 10:03:08 | NULL          |
| 3  | 2           | 0005 | 2014-10-03 10:10:16 | NULL          |
| 4  | 2           | 0006 | 2014-10-03 10:10:18 | NULL          |
+----+-------------+------+---------------------+---------------+ 

我不确定我需要为此查询做什么样的连接。有什么想法吗?

3 个答案:

答案 0 :(得分:1)

我会用相关的子查询来做这件事。对于带有" 1"的每一行,您需要下一行用于相同的"代码"和" 2":

select t.*,
       (select t2.created
        from table t2
        where t2.code = t.code and
              t2.id > t.id and
              t2.location_id = 2 and
        order by t2.id desc
        limit 1
       ) as exitdte
from table t;

然后,您可以使用timestampdiff()之类的内容来获取时间差异,avg()以获得适当的平均值。

出于性能原因,您应该在table(code, location, id, created)上有一个索引。

答案 1 :(得分:0)

我们可以在同一张桌子上进行自我加入,以获取每个代码的入场时间和退出时间列表。 这两次之间的差异可以视为平均值。

这是SQL小提琴:http://www.sqlfiddle.com/#!2/5a4d4

select t1.code, avg( t1.created - t2.created) average
    from Table1 t1
    Join Table1 t2
        on t1.code = t2.code
        and t1.location_id = 2
        and t2.location_id =1
    group by t1.code

答案 2 :(得分:0)

也许是这样的:(警告,oldschool SQL :))

SELECT AVG(b.created - a.created) as average
  FROM (SELECT created FROM table WHERE location_id = (should be a parameter) AND code = '0005') AS a,
       (SELECT created FROM table WHERE location_id = (should be a parameter) AND code = '0006') AS b