PHP - MYSQL:每个月的第一个到最后一个月的过去12个月

时间:2015-02-10 00:09:39

标签: php mysql

我所参与的项目需要获得过去12个月中每个月的平均发票总额。我可以通过12个查询(每个月1个)轻松获得我需要的东西,但它非常难看,我最终得到12个独特的变量(id而不是循环),我知道有更好的方法。

任何人都可以帮助您获得以下内容的最佳方式:

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'

等...

我在图表上绘制这些图,所以我需要每月一个数据点。

最终结果如下:

Jan: $2323
Feb: $3523
March: $6453

等......但是从本月起12个月前开始。

谢谢。

P.S。对于参考,这是我在过去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);
    }

我需要与上述相同的想法,但过去12个月。每个月的平均值。

1 个答案:

答案 0 :(得分:0)

您可以使用MONTHNAME功能并按以下方式分组:

http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_month

你的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)