[英]PHP - MYSQL: Last 12 months first to last day of each month
A project I am on has the need to get an average invoice total for each of the the last 12 months. 我参与的一个项目需要获得最近12个月中每个月的平均发票总额。 I can easily get what I need by doing 12 queries (1 for each month), but its very ugly, I end up with 12 unique variables(id rather have a loop ), and I know there is a better way.
我可以通过执行12个查询(每个月1个查询)轻松地获得所需的信息,但是非常丑陋,我最终得到12个唯一变量(id而不是具有loop),而且我知道有更好的方法。
Can anyone help with the best way to get the following: 任何人都可以以最佳方式获得以下帮助:
SELECT AVG(invoice_total) FROM invoice WHERE date between '2015-01-01' AND '2015-01-31'
SELECT AVG(invoice_total) FROM invoice WHERE date between '2015-02-01' AND '2015-02-28'
SELECT AVG(invoice_total) FROM invoice WHERE date between '2015-03-01' AND '2015-03-31'
etc... 等等...
Im plotting these on a graph, so I need a data point for each month. 我将它们绘制在图表上,因此我每个月都需要一个数据点。
End result would be something like: 最终结果将是这样的:
Jan: $2323
Feb: $3523
March: $6453
ect... but would start 12 months ago from the current month. 等等...但将从当月的12个月前开始。
Thank you. 谢谢。
PS For refrence, this is how I am plotting the last 90 days: 附注:为了方便起见,这是我最近90天的绘制方式:
$get_unconfirmed_appointments = "
SELECT total
, invoice_date
FROM invoice
WHERE clinic_id = 20
AND invoice_date >= '$date'
AND invoice_date <= '$date_two'
ORDER
BY invoice_date ASC
";
$result = $conn->query($get_unconfirmed_appointments) or die($conn->error.__LINE__);
while($row = $result->fetch_assoc()) {
$totals[$row['invoice_date']][] = $row['total'];
}
$sub_arrays = array_chunk($totals, 3);
foreach ($sub_arrays as $threedays) {
foreach ($threedays as $value) {
foreach ($value as $val) {
$all[] = $val;
}
}
$average = array_sum($all) / count($all);
$data_point=round($average,2);
plot($data_point);
}
I need the same idea as above, but for the last 12 months. 我需要与上述相同的想法,但需要持续12个月。 Average for each month.
每个月的平均值。
You can use the MONTHNAME function and group by that: 您可以使用MONTHNAME函数并按以下方式分组:
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_month
You SQL will be something like that: 您的SQL将是这样的:
SELECT AVG(invoice_total), MONTHNAME(invoice_date) FROM invoice WHERE invoice_date BETWEEN '2014-11-11' AND '2015-02-09' GROUP BY MONTHNAME(invoice_date)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.