我需要计算一个日期时间列之间的日期/时间差异

时间:2010-04-16 12:04:29

标签: datetime mysql

详情。 我的笔记表有以下几列。

ID       - INT(3)
Date     - DateTime
Note     - VARCHAR(100)
Tile     - Varchar(100)
UserName -  Varchar(100)

现在,此表将包含NOTES以及UserName在指定日期/时间输入的标题。

我需要计算相同列中TWO ROWS之间的DateTimeDifference

例如,上表在表格中有这个信息。

64, '2010-03-26 18:16:13', 'Action History', 'sending to Level 2.', 'Salman Khwaja'
65, '2010-03-26 18:19:48', 'Assigned By', 'This is note one for the assignment of RF.', 'Salman Khwaja'
66, '2010-03-27 19:19:48', 'Assigned By', 'This is note one for the assignment of CRF.', 'Salman Khwaja'

现在我需要在使用MYSQL的查询报告中使用以下结果集。

TASK                -  TIME Taken
ACTION History      - 2010-03-26 18:16:13
Assigned By         - 00:03:35
Assigned By         - 25:00:00

更聪明的方法是

TASK                -  TIME Taken
ACTION History      - 2010-03-26 18:16:13
Assigned By         - 3 minutes 35 seconds
Assigned By         - 1 day, 1 hour.

如果有人可以将PLAIN QUERY和PHP代码一起嵌入,我将不胜感激。

3 个答案:

答案 0 :(得分:1)

<?php
$start = new DateTime('2009-01-01 00:00:00'); // 31 days
$time_span = $start->diff(new DateTime('2009-02-01 00:00:00'));
var_dump($time_span); // returns '1 month'

$start = new DateTime('2009-02-01 00:00:00'); //28 days
$time_span = $start->diff(new DateTime('2009-03-01 00:00:01'));
var_dump($time_span); // returns '1 month'
?>

答案 1 :(得分:0)

答案 2 :(得分:0)

看起来您想按案例编号分组。

使用您的架构和示例数据,我认为这正是您想要的:

SELECT  t1.ID, t1.title AS task, t1.username,
  IFNULL(CONCAT(TIMESTAMPDIFF(MINUTE, t2.currentDate, t1.currentDate)), t1.currentdate) AS time_taken
FROM tps_trans_support_notes t1
LEFT JOIN tps_trans_support_notes t2
  ON t2.currentdate < t1.currentdate AND
    t2.ID <> t1.ID AND
    t2.casenumber = t1.casenumber
LEFT JOIN tps_trans_support_notes t3
  ON t3.casenumber = t1.casenumber AND
    t3.ID <> t1.ID AND t3.ID <> t2.ID AND
    t3.currentdate > t2.currentdate AND
    t3.currentdate < t1.currentdate
WHERE t3.ID IS NULL AND
  t1.casenumber = '21'
ORDER BY t1.ID

首先,查询将开始时间和结束时间放入同一行,不包括两者之间出现时间的行,然后显示差异。

查询仅显示以分钟为单位的差异,但您可以使用其他DateTime函数来扩展它。

相关问题