我正在为我运行的服务编写统计脚本。我想计算过去3天,每周,每月和每年的平均每天行数。我的基本思想是这样的,以获得平均值:
<?php
function getDayNumber($day)
{
$start = strtotime("last monday");
$q = mysql_query(sprintf("SELECT COUNT(*) as count FROM mytable WHERE dayname(datetime) = "%s" AND unix_timestamp(datetime) > %s",$day,$start));
$row = mysql_fetch_assoc($q);
return $row['count'];
}
$monday = getDayNumber("Monday");
$tuesday = getDayNumber("Tuesday");
$wednesday = getDayNumber("Wednesday");
$thursday = getDayNumber("Thursday");
$friday = getDayNumber("Friday");
$average = ($monday+$tuesday+$wednesday+$thursday+$friday)/5;
?>
以上只是从我脑海中写下的伪代码。我不能想出一个更好的方法。
这可以通过嵌套/加入查询来实现吗?我需要能够每天,每周,每月......等基础上进行。我想如果我能找到一种方法来提取MySQL中的所有数据,我可以将所有 count(*)组合在一起并通过响应数量来划分它们。
这可行吗?
感谢任何帮助 - 谢谢大家!
答案 0 :(得分:0)
我建议找到每个数据集的日期范围,然后运行查询。希望这会有所帮助。
<?php
/**
* Get the average number of rows that were created
* during the given date range.
*
* @param string $range The date range to look for
* @return integer The average number of rows created in the given range
*/
function getAverageRows($range)
{
$date_begin = null;
$date_end = null;
switch($range)
{
case 'year':
// Calculate the beginning and end datetime of the past year
$date_begin = FIRST_DAY_OF_YEAR . ' 00:00:00';
$date_end = LAST_DAY_OF_YEAR . ' 23:59:59';
break;
case 'month':
// Calculate the beginning and end datetime of the past month
$date_begin = FIRST_DAY_OF_MONTH . ' 00:00:00';
$date_end = LAST_DAY_OF_MONTH . ' 23:59:59';
break;
case 'week':
// Calculate the beginning and end datetime of the past week
$date_begin = FIRST_DAY_OF_WEEK . ' 00:00:00';
$date_end = LAST_DAY_OF_WEEK . ' 23:59:59';
break;
default:
// Calculate the beginning and end datetime of the past three days
$date_begin = SEVENTY_SIX_HOURS_AGO;
$date_end = now();
break;
}
$query = "SELECT COUNT(*) FROM mytable WHERE datetime >= '{$date_begin}' AND datetime <= '{$date_end}'";
// Get and return query results
}
echo "Average Rows:<br/>";
echo "Past three days: " . getAverageRows() . "<br/>";
echo "Past week: " . getAverageRows('week') . "<br/>";
echo "Past Month: " . getAverageRows('month') . "<br/>";
echo "Past Year: " . getAverageRows('year') . "<br/>";