简体   繁体   English

行之间的时差(MySQL)

[英]Time difference between rows (MySQL)

I have a table like this (other columns are removed): 我有一个这样的表(其他列已删除):

+---------+----------+---------------------+---------------------+
| id      | party_id | begintime           | endtime             |
+---------+----------+---------------------+---------------------+
| 1528604 |    10000 | 2011-09-22 15:33:52 | 2011-09-23 14:09:34 |
| 1528605 |    10000 | 2011-09-23 14:12:48 | 2011-09-23 14:12:50 |
| 1528606 |    10000 | 2011-09-23 14:14:36 | 2011-09-23 15:29:59 |
| 1528607 |    10000 | 2011-09-23 15:33:50 | 2011-09-26 09:52:19 |
| 1528608 |    10000 | 2011-09-26 09:54:59 | 2011-09-26 11:20:55 |
| 1528609 |    10000 | 2011-09-26 11:23:30 | 2011-09-26 11:39:44 |
| 1528610 |    10000 | 2011-09-26 11:47:19 | 2011-09-26 12:45:00 |
| 1528611 |    10000 | 2011-09-26 12:47:22 | 2011-09-26 14:28:53 |
| 1528612 |    10000 | 2011-09-26 14:31:38 | 2011-09-26 15:26:08 |
| 1528613 |    10000 | 2011-09-26 15:29:37 | 2011-09-26 18:15:00 |
| 1528614 |    10000 | 2011-09-26 18:16:48 | 2011-09-26 19:38:11 |
| 1528615 |    10000 | 2011-09-26 19:40:19 | 2011-09-26 22:23:37 |
+---------+----------+---------------------+---------------------+

I need to calculate a time difference between endtime and begintime in the next row. 我需要计算之间的时间差endtimebegintime下一排。 Expected result should be like this: 预期结果应该是这样的:

194
106
231
......

ie 194 = timestampdiff(second,'2011-09-23 14:09:34','2011-09-23 14:12:48') and so on. 194 = timestampdiff(second,'2011-09-23 14:09:34','2011-09-23 14:12:48')依此类推。

I've tried this: 我已经试过了:

select timestampdiff(second, t1.begintime, t2.endtime) 
    from doses t1 join doses t2
    on t2.id=(select t2.id from doses t2 where t2.id>t1.id limit 1) 
        and t2.party_id=10000
        and t1.party_id=10000;

but the result has too many values. 但结果值太多。 What an I doing wrong? 我做错了什么?

Not sure the exact result you want to achieve, but you can try this: 不确定要获得的确切结果,但是您可以尝试以下操作:

select t1.id, t1.`party_id`, t1.begintime, t1.endtime, timestampdiff(second,t1.endtime, t2.begintime) `timediff`
from (
  select test.*, @rowno1 := @rowno1 + 1 rowno
  from test
  cross join (select @rowno1 := 1) t
  order by id
) t1
left join (
  select test.*, @rowno2 := @rowno2 + 1 rowno
  from test
  cross join (select @rowno2 := 0) t
  order by id
) t2 on t1.rowno = t2.rowno

Here is SQLFiddle Demo. 这是SQLFiddle演示。

I have not try it myself, but I think if we can select one next row using dependent sub query we can subtract its value. 我自己还没有尝试过,但是我认为,如果我们可以使用相关子查询选择下一行,则可以减去其值。

SELECT 
    timestampdiff(second, t1.begintime, 
       (SELECT t2.endtime 
       FROM doses t2
       WHERE 
          t2.id>t1.id AND
          t2.party_id = t1.party_id
       LIMIT 1)) 
FROM doses t1 
WHERE t1.party_id=10000;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM