根据时差选择子查询中下一行的字段

时间:2015-01-11 11:51:48

标签: mysql sql

我试图从下一行抓取一个字段,然后计算当前行字段和Mysql中下一行字段之间的时差。但它总是给我一个60小时的非常大的时间。由于这不止一天,所以必须是错误的。

我的查询是这样的:

select DATE_FORMAT( last_call, '%d' ) AS 'day',
    COUNT(call_id) as id,

   SEC_TO_TIME(SUM((select timestampdiff(second, calls.last_call, c2.last_call)
    from calls c2
    where c2.calling_agent = calls.calling_agent and
          c2.last_call > calls.last_call and
          timestampdiff(second, calls.last_call, c2.last_call) > 600
    order by c2.last_call
    limit 1
   ))) brakes

来自电话 WHERE calling_agent = 9  AND last_call> DATE_SUB(now(),INTERVAL 12个月) GROUP BY EXTRACT(来自last_call的日子)

1 个答案:

答案 0 :(得分:1)

您可以使用相关子查询获取下一个值:

select c.*,
       (select c2.last_call
        from calls c2
        where c2.calling_agent = c.calling_agent and
              c2.last_call > c.last_call
        order by c2.last_call
        limit 1
       ) next_last_call
from calls c;

如果您愿意,可以使用timestampdiff()来获取下一个和当前之间的差异:

select c.*,
       (select timestampdiff(second, c.last_call, c2.last_call)
        from calls c2
        where c2.calling_agent = c.calling_agent and
              c2.last_call > c.last_call
        order by c2.last_call
        limit 1
       ) diff_in_secs
from calls c;

然后应用你想要的任何逻辑(也许使用它作为子查询)。