总结DATETIMES和分组

时间:2011-07-14 23:23:39

标签: mysql datetime sum

这是我在DATETIME中输入和输出的表格。我想按p_ID对TIMEDIFF进行求和,并按p_ID对它们进行分组。

t_ID p_ID   t_IN                     t_OUT
1    1      2011-07-13 18:54:56      2011-07-13 20:16:12
2    1      2011-07-14 09:26:56      2011-07-14 09:46:02
3    1      2011-07-14 10:06:39      2011-07-14 10:56:31
4    3      2011-07-14 13:07:04      2011-07-14 13:58:35

我尝试了一些MySQL命令无济于事......我的最后一次尝试看起来像这样:

SELECT p_ID, TIME_FORMAT(SUM(TIMEDIFF(t_OUT,t_IN)),'%H:%i') AS time FROM timeclock GROUP BY p_ID

我猜我的命令不是每个p_ID每个记录的总和...任何帮助?

3 个答案:

答案 0 :(得分:1)

想出来:

$timeDiffReq = mysql_query("CREATE VIEW totals AS SELECT p_ID, TIME_TO_SEC(TIMEDIFF(t_OUT,t_IN)) AS time FROM timeclock");
$timeTotalReq = mysql_query("SELECT p_ID, SEC_TO_TIME(SUM(time)) AS timetotals FROM totals GROUP BY p_ID");
while($row = mysql_fetch_array($timeTotalReq)) {
echo "<div class=\"clockInOut\"><div id=\"name\">" . $row['p_ID'] . " - " . $row['timetotals'] . "</div></div>";}
$timeTotalDrop = mysql_query("DROP VIEW totals");

答案 1 :(得分:0)

试试这个:

SELECT p_ID,
       SUM(TIMESTAMPDIFF(HOUR, t_OUT, t_IN)) AS time
FROM timeclock
GROUP BY p_ID;

现在只有几个小时,不过你可以用MINUTE替换它。

答案 2 :(得分:0)

你很接近,你需要一个两步的方法,因为格式需要在获得SUM之后完成,否则会妨碍聚合时间差异。
试试这个:

SELECT p_ID, TIME_FORMAT(minutes,'%H:%i') as time
FROM (SELECT p_ID, SUM(TIMESTAMPDIFF(MINUTE, t_OUT, t_IN)) AS minutes
    FROM timeclock
    GROUP BY p_ID) x;

不确定TIME_FORMAT的格式,但此查询应该关闭。