我正在尝试查询 mysql 以获取多个记录的平均 SUM 时间(取自日期时间字段),以获得如下输出:22: 38
我的日期时间字段 checkin_time 包含如下数据:
2012-03-16 22:48:00 // the time here: 22:48 is what's interesting to me
2012-03-16 02:28:32
2012-03-16 00:28:47
0000-00-00 00:00:00
我的计划是从所有日期时间字段中提取和选择总和时间,然后将总和转换为 unix 时间戳,将总和除以记录总数,最后将其转换回时间格式。然而,这(见下面的代码)什么也没给我,没有错误,什么都没有。我还意识到像:0000-00-00 00:00:00 这样的空字段在生成相关数据时不会被考虑在内。
谁能帮我指出错误,或者解释一下你将如何做到这一点的理论?这是我到目前为止得到的:
编辑:感谢Damiqib建议一个有效的 SQL 查询,但仍然不完全正确。下面的代码在应该是 23:15时输出01:00。
$getCheckinTime = mysql_query("SELECT COUNT(id), SEC_TO_TIME( AVG( TIME_TO_SEC( `checkin_time` ) ) ) AS averageTime FROM guests WHERE checkin_time != '0000-00-00 00:00:00'") or die(mysql_error());
while($checkIn = mysql_fetch_array($getCheckinTime)) {
$timestamp = strtotime($checkIn['averageTime']);
$UnixTimeStamp = date("Y-m-d H:i:s", $timestamp); //converting to unix
$avgUnix = $UnixTimeStamp / $checkIn['COUNT(id)']; // calculating average
$avgTime = date('H:i', $avgUnix); // convert back to time his format
echo $avgTime; //outputs 01:00, got to be incorrect should be 23:15 something
}
提前致谢
编辑:解决方案(感谢 Damiqib):
$avgCheckinTime = array();
$getCheckinTime = mysql_query("SELECT TIME(`checkin_time`) AS averageTime FROM guests WHERE checkin_time != '0000-00-00 00:00:00'") or die(mysql_error());
while($checkIn = mysql_fetch_array($getCheckinTime)) {
array_push($avgCheckinTime, $checkIn['averageTime']);
}
// = array('22:00:00', '22:30:00'...)
$times = $avgCheckinTime;
$fromReplace = array('22' => '00',
'23' => '01',
'00' => '02',
'01' => '03',
'02' => '04',
'03' => '05',
'04' => '06',
'05' => '07');
$timeSum = 0;
//Iterate through all given times and convert them to seconds
foreach ($times as $time) {
if (preg_match ('#^(?<hours>[\d]{2}):(?<mins>[\d]{2}):(?<secs>[\d]{2})$#',$time, $parse)) {
$timeSum += (int) $fromReplace[$parse['hours']] * 3600 + (int) $parse['mins'] * 60 + (int) $parse['secs'] . '<br />';
//echo $time . ' ' . ($fromReplace[$parse['hours']] *3600) . '<br />';
}
}
$toReplace = array('00' => '22',
'01' => '23',
'02' => '00',
'03' => '01',
'04' => '02',
'05' => '03',
'06' => '04',
'07' => '05');
$time = explode(':', gmdate("H:i:s", $timeSum / count($times)));
$averageCheckinTime = $toReplace[$time[0]] . ':' . $time[1] . ':' . $time[2];
//This is the final average time biased between 22-05
echo $averageCheckinTime;