如何在表格中获得最近12个月的销售小计?

I have this code so far which gives me the subtotals for each product for a given month.

 <?php
    include("dbaseconn.php"); 




    $query = "SELECT product, SUM(qty) FROM sh_orders GROUP BY product"; 

    $result = mysql_query($query) or die(mysql_error());

    // Print out result
    while($row = mysql_fetch_array($result)){
      echo "<table width='1050'>"  ;
      echo "<td width='400'>";
        echo "". $row['product']. " ";
      echo "</td>";
      echo "<td>";
      echo "". $row['SUM(qty)']. "" ;
      echo "</td>";
        echo "<br />";
    }
    ?>

TABLE STRUCTURE

CREATE TABLE IF NOT EXISTS `sh_orders` (
  `building` varchar(50) NOT NULL,
  `qty` varchar(5) NOT NULL,
  `product` varchar(50) NOT NULL,
  `order_id` bigint(5) NOT NULL AUTO_INCREMENT,
  `unik` varchar(50) NOT NULL,
  `order_date` varchar(25) NOT NULL,
  `co_id` varchar(20) NOT NULL,
  UNIQUE KEY `unik` (`unik`),
  UNIQUE KEY `id` (`order_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=11 ;

I want to show the last 12 months sales - SUM (qty) does that for me, but I need to see each month separately with each product and its total sales for that month. I need this in one table showing each month with each product and total for that month

EXPECTED RESULT
Month:    January 2012    Feb 2012   Marc 2012
Product1: 124                105         76
Product2:  34                 23         56
Product3:  12                  5          6

I am new to this so please show patience if I ask a million questions.

change your query to

  $query = "SELECT product, SUM(qty) FROM sh_orders where Product_month between '2011-01-01' and '2012-01-01' GROUP BY product"; 

This is the query that you need:

SELECT order_date, product, SUM(qty) as sum_qty
FROM sh_orders 
WHERE order_date > DATE_SUB( CURDATE(), INTERVAL 1 YEAR)
GROUP BY YEAR(order_date), MONTH(order_date), product

sqlfiddle


The result is an array in this format:

array(
    array(
        'order_date' => '2012-09-02',
        'product'    => 'p2',
        'sum_qty'    => '2'
    ),
    array(
        // etc...
    )
);

You just have to loop through it and display the result as a table. If you have problems with creating the table it would be better to accept an answer here and ask a new question because it's more related to html, loops and arrays.

SELECT product,sum(qty),DATE_FORMAT(product_month, '%Y-%m') as month 
FROM sh_orders 
WHERE product_month BETWEEN DATE_SUB(now(), INTERVAL 12 MONTH) 
AND now() group by  DATE_FORMAT(product_month, '%Y%m'),product

Each product have some quantity in same month and different days. First group by month, same product quantity summed each month. Second group by product, avoid product duplication in same month