MySQL - 查找不同Id的行之间的时差

时间:2018-05-28 09:13:03

标签: mysql sql

我有一张由以下数据组成的表格:

ID   status-before             status-current         DATE-timestamp         
5    Un-Assigned                Assigned              2013-12-17 14:14:04
5    Assigned                   Completed             2013-12-21 14:14:04
7    Un-Assigned                Assigned              2014-01-02 14:14:04 
7    Assigned                   Completed             2014-01-21 14:14:04
7    Completed                  Locked                2014-01-21 14:14:04
8    Un-Assigned                Assigned              2014-12-21 14:14:04
8    Assigned                   Completed             2014-12-27 14:14:04

我使用group by来分组ID和排序的时间戳字段。我不知道如何使用rownum(或任何其他方法)来计算只有具有相同id的行的时间差。

我希望我的最终输出如下

ID   status-before              status-current     DATE-timestamp       Time Diff(Hours)
5    Un-Assigned                Assigned        2013-12-17 14:14:04    xx
5    Assigned                   Completed       2013-12-21 14:14:04    xx
7    Un-Assigned                Assigned        2014-01-02 14:14:04    xx 
7    Assigned                   Completed       2014-01-21 14:14:04    xx
7    Completed                  Locked          2014-01-21 14:14:04    xx
8    Un_Assigned                Assigned        2014-12-21 14:14:04    xx
8    Assigned                   Completed       2014-12-27 14:14:04    xx

3 个答案:

答案 0 :(得分:0)

使用TIMEDIFF返回hours:minutes:secondsDATEDIFF返回days

SELECT TIMEDIFF('complete.TIMESTAMP','assign.TIMESTAMP');
SELECT DATEDIFF('complete.TIMESTAMP','assign.TIMESTAMP');

答案 1 :(得分:0)

如果您对Assigned和Completed之间的时差感兴趣,可以使用下面的脚本。

SELECT a.ID, 
   b.[status-after], 
   a.[DATE-timestamp], 
   DATEDIFF(Hour, a.[DATE-timestamp], b.[DATE-timestamp]) AS TimeDiff_Hours
FROM YourTable a
JOIN YourTable b 
ON a.ID = b.ID AND b.[status-after] = 'Completed'
WHERE a.[status-after] = 'Assigned'

答案 2 :(得分:0)

据推测,您希望时间差异为ID的 next 状态。让我假设版本8之前的MySQL。您可以使用相关子查询获取下一个时间戳,然后使用timestampdiff()

select t.*,
       timestampdiff(hour, date_timestamp, next_datetimestamp) as diff_hours
from (select t.*,
             (select t2.date_timestamp
              from t t2
              where t2.id = t.id and
                    t2.date_timestamp > t.date_timestamp
              order by t2.date_timestamp asc
             ) as next_date_timestamp
      from t
     ) t;

如果您使用的是MySQL 8.0,则可以使用lead()函数简化此逻辑。