查找表中2行之间的时差

时间:2018-01-26 14:48:12

标签: mysql sql

LogRowID    Stamp                    Comment
55170   1/25/2018 11:04:29 PM   END uspArchiveBFAM run
55120   1/25/2018 5:30:20 PM    Begin BFAM Archive process
55119   1/24/2018 11:17:36 PM   END uspArchiveBFAM run
55069   1/24/2018 5:30:25 PM    Begin BFAM Archive process
55068   1/23/2018 10:59:48 PM   END uspArchiveBFAM run
55018   1/23/2018 5:30:07 PM    Begin BFAM Archive process
55017   1/19/2018 10:38:56 PM   END uspArchiveBFAM run
54967   1/19/2018 5:30:08 PM    Begin BFAM Archive process

每个进程的LogRowID增加50。 (从头到尾)

我想创建一个表,其中包含流程日期和当天流程的持续时间。 (2栏)

WANT:

日期| DURATION

1/25/2018 | 5时34分09秒
1/24/2018 | 5时47分十一秒
1/23/2018 | 5点29分41秒

编辑: 这就是我到目前为止所做的:

select  distinct date_format(stamp, '%m/%d/%y') as 'Date',
(select TIMEDIFF((select stamp from bfam_archive_log where (date(stamp) = subdate(CURRENT_DATE,1) and comment ='END uspArchiveBFAM run')),
(select stamp from bfam_archive_log where (date(stamp) = subdate(CURRENT_DATE,1) and comment = 'Begin BFAM Archive Process')))) as 'Duration'
from bfam_archive_log

Current Code

我不知道如何计算超过1对日期时间的差异。

1 个答案:

答案 0 :(得分:0)

这里有很多假设,但无论如何......

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(LogRowID SERIAL PRIMARY KEY
,Stamp DATETIME 
,Comment VARCHAR(12) NOT NULL
);

INSERT INTO my_table VALUES
(55170,'2018-01-25 11:04:29' ,'END'),
(55120,'2018-01-25 05:30:20' ,'Begin'),
(55119,'2018-01-24 11:17:36' ,'END'),
(55069,'2018-01-24 05:30:25' ,'Begin'),
(55068,'2018-01-23 10:59:48' ,'END'),
(55018,'2018-01-23 05:30:07' ,'Begin'),
(55017,'2018-01-19 10:38:56' ,'END'),
(54967,'2018-01-19 05:30:08' ,'Begin');

SELECT x.*
     , TIMEDIFF(MIN(y.stamp),x.stamp) diff 
  FROM my_table x 
  JOIN my_table y ON DATE(y.stamp) = DATE(x.stamp) 
   AND y.stamp > x.stamp 
   AND y.comment = 'end' 
 WHERE x.comment = 'begin' 
 GROUP 
    BY x.logrowid;
+----------+---------------------+---------+----------+
| LogRowID | Stamp               | Comment | diff     |
+----------+---------------------+---------+----------+
|    54967 | 2018-01-19 05:30:08 | Begin   | 05:08:48 |
|    55018 | 2018-01-23 05:30:07 | Begin   | 05:29:41 |
|    55069 | 2018-01-24 05:30:25 | Begin   | 05:47:11 |
|    55120 | 2018-01-25 05:30:20 | Begin   | 05:34:09 |
+----------+---------------------+---------+----------+