开发者

Summing DATETIMES and grouping

开发者 https://www.devze.com 2023-03-20 05:48 出处:网络
Here\'s a table I have with DATETIMEs in and out.I\'d like to sum the TIMEDIFFs per p_ID and group them by p_ID.

Here's a table I have with DATETIMEs in and out. I'd like to sum the TIMEDIFFs per p_ID and group them by 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      20开发者_StackOverflow11-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

I've tried a few MySQL commands to no avail... My last attempt looked like this:

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

I'm guessing my command is not summing per record per p_ID... Any help?


Figured it out:

$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");


Try this:

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

It's only hours for now, though you could replace it by MINUTEs.


You were close, you just need a two-step approach, because the formatting needs to be done after getting the SUM, otherwise it gets in the way of aggregating the time diff.
Try this:

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;

Not sure about the formatting of TIME_FORMAT, but this query should be close.

0

精彩评论

暂无评论...
验证码 换一张
取 消