使用mysql,计算行之间的UNIX时差

时间:2017-01-25 23:04:04

标签: mysql

enter image description here

在此表中,有100个不同的receipt_id。每个receipt_id都有多个状态。我想计算status_code DWRESULT_INIT和DWRESULT_SAVED之间的时差。我想通过receipt_id对结果进行分组,这样我就可以看到DB中所有100个receipt_id的时差。我是mysql的新手,我不知道如何实现这一目标。

2 个答案:

答案 0 :(得分:1)

使用mysql的timestampdiff()函数计算差异,并使用from_unixtime()函数将时间戳转换为日期时间数据类型。要将2个状态代码放入单个记录中,请使用子查询仅获取init记录并将其连接回已过滤保存的表:

select t1.receipt_id, timestampdiff(second, from_unixtime(t2.event_time), from_unixtime(t1.event_time)) as diff
from yourtable t1
inner join
    (select receipt_id, event_time
     from yourtable
     where status_code='DWRESULT_INIT') t2 on t1.receipt_id=t2.receipt_id
where t1.status_code='DWRESULT_SAVED'

答案 1 :(得分:0)

enter image description here

SELECT 
T1.type,
if(TIMESTAMPDIFF(MINUTE, FROM_UNIXTIME(T1.start_time),FROM_UNIXTIME(T1.end_time)) IS NULL,0,TIMESTAMPDIFF(MINUTE, FROM_UNIXTIME(T1.start_time),FROM_UNIXTIME(T1.end_time))) AS totalTimeInMinute,
T1.start_time AS startTime,
T1.end_time AS endTime
FROM (SELECT type,createdAt AS start_time,(SELECT createdAt FROM Worktime WHERE date='2020-10-08' AND createdAt > start_time LIMIT 1) AS end_time FROM Worktime 
WHERE date='2020-10-08') AS T1

enter image description here