总结DATEDIFF字段

时间:2014-08-04 10:37:59

标签: mysql

如何使用此查询汇总总时间:

    SELECT 
`tblproduction`.`ID`, 
`tblproduction`.`OrderID`, 
`tblproduction`.`ProductID`,
`tblproduction`.`Start`,
`tblproduction`.`End`,
(TIME_TO_SEC(TIMEDIFF(`tblproduction`.`EndDateTime`,`tblproduction`.`StartDateTime`))) AS TotTime
FROM `tblproduction` 
LEFT OUTER JOIN `tblproductionlog` ON `tblproduction`.`ID` = `tblproductionlog`.`ID` 
WHERE tblproduction.OrderID = 'a'
GROUP BY `tblproduction`.`ID` 

结果表是:

+--------+---------+---------+---------+---------+
| Id     | OrderID | Start   | End     | TotTime |
+--------+---------+---------+---------+---------+
| 1      |   a     |17:17:50 |17:28:21 |631      |  
+--------+---------+---------+---------+---------+  
| 2      |   a     |17:34:55 |19:49:00 |8045     |
+--------+---------+---------+---------+---------+ 

我想要的是:

+---------+---------+
| OrderID | TotTime | 
+---------+---------+
|   a     | 8676    |  
+---------+---------+

我应该在查询中更改什么?

2 个答案:

答案 0 :(得分:2)

删除不需要的列并总结总时间,第三个GROUP BY OrderID,而不是ID。

SELECT 
    `tblproduction`.`OrderID`, 
    SUM(TIME_TO_SEC(TIMEDIFF(`tblproduction`.`EndDateTime`,`tblproduction`.`StartDateTime`))) AS TotTime
FROM `tblproduction` 
LEFT OUTER JOIN `tblproductionlog` ON `tblproduction`.`ID` = `tblproductionlog`.`ID` 
WHERE tblproduction.OrderID = 'a'
GROUP BY `tblproduction`.`OrderID` 

答案 1 :(得分:1)

您可以简单地写: -

SELECT 
`tblproduction`.`OrderID`, 
SUM(TIME_TO_SEC(TIMEDIFF(`tblproduction`.`EndDateTime`,`tblproduction`.`StartDateTime`))) AS TotTime
FROM `tblproduction` 
LEFT OUTER JOIN `tblproductionlog` ON `tblproduction`.`ID` = `tblproductionlog`.`ID` 
WHERE tblproduction.OrderID = 'a'
GROUP BY `tblproduction`.`OrderID`;

这可以帮到你。