Php 按天选择多行数的平均值
我正在为我运行的服务编写一个统计脚本。我想计算出过去3天,每周、每月和每年每天的平均行数。我的基本想法是这样的:抓住平均数:Php 按天选择多行数的平均值,php,mysql,Php,Mysql,我正在为我运行的服务编写一个统计脚本。我想计算出过去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_t
<?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;
?>
以上只是我头脑中编写的psuedo代码。但是我想不出更好的方法了
这可以通过嵌套/联接查询实现吗?我需要能够做到每天,每周,每月。。。etc基础。我想如果我能找到一种方法来提取MySQL中的所有数据,我可以将所有count(*)加在一起,然后通过响应的数量来划分它们
这是否可行
感谢您的帮助,谢谢大家 我建议找到每个数据集的日期范围,然后运行查询。希望这有帮助
<?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/>";
添加具有预期结果的示例数据可能会有帮助。对不起,您想要什么类型的数据?表中的数据是不相关的,对吗?我只想获取计数,并根据当天计算平均值。这里有一个名为“datetime”的字段,它是一个标准的日期/时间。对不起,我不认为我完全理解它是如何工作的。你使用的常数,我猜它们是在别处定义的?还有,这是如何获取平均值的?从我看到的情况来看,这将获取这些时段之间的总行数。我需要计算出给定时间段内的平均行数。