MySQL使用多行数据计算2个日期之间的时间

时间:2017-02-25 13:21:14

标签: mysql timestampdiff

我有一个包含2列date_picked_begindate_picked的表格,并且会有多行包含每个列的日期。

如何使用TIMESTAMPDIFF获取所有数据行中日期之间的秒数差异。

我尝试过以下查询,但它只返回第一行的秒数差异。 (这是别名total_picking_waiting_time,试图获得总时间)。

SELECT COUNT(pi.pi_id) AS num_picking_waiting_time,
AVG(TIMESTAMPDIFF(SECOND, pi.date_picked_begin, pi.date_picked)) AS average_picking_waiting_time,
TIMESTAMPDIFF(SECOND, pi.date_picked_begin, pi.date_picked) AS total_picking_waiting_time
FROM (SELECT pi_id, type, date_picked_begin, date_picked, picker FROM pickwave_items) as pi
WHERE pi.type = 'Picking (Waiting Time)' AND DATE(pi.date_picked) = '2017-02-25' AND pi.picker = 1

另外,我一直假设此查询获得了所有行中两个日期之间的平均时间。是这样的吗?由于它没有像我预期的那样返回总时间,我现在认为它不是。

谢谢

1 个答案:

答案 0 :(得分:1)

首先,FROM中的子查询是不必要的。它为查询增加了冗长,并且实际上减慢了它(因为MySQL实现了这样的子查询)。

然后,要获得总选择时间,请使用SUM()

SELECT COUNT(pi.pi_id) AS num_picking_waiting_time,
       AVG(TIMESTAMPDIFF(SECOND, pi.date_picked_begin, pi.date_picked)) AS average_picking_waiting_time,
       SUM(TIMESTAMPDIFF(SECOND, pi.date_picked_begin, pi.date_picked)) AS total_picking_waiting_time
FROM pickwave_items as pi
WHERE pi.type = 'Picking (Waiting Time)' AND
      DATE(pi.date_picked) = '2017-02-25' AND
      pi.picker = 1;