The simplest way:
SELECT EXTRACT(YEAR_MONTH FROM FROM_UNIXTIME(`Date`)) AS year_mo, `Name` AS name, SUM(`Apples`) AS sum_apples FROM apples_table GROUP BY 1,2 ORDER BY 1,3 DESC;
You should probably use the DATETIME column to store your dates, but you can use the FROM_UNIXTIME() function to convert values โโfor use with EXTRACT . See the MySQL date / time documentation for more information.
This query will give you more than two lines per month, which you should process in a PHP loop that reads the results, keeping track of how many times in a row you see the same month and discarding the lines as necessary. I think this is a much better way to deal with your problem than using 12 separate queries.
If your table has only 40 rows, performance will not be a problem unless you do something really bad.
If you really want to delve into the secret SQL syntax needed to get exactly the results you want in a single query, see this article . Handling tacks and other marginal cases will be so messy.
Edit is the idea of โโPHP code:
$query = mysql_query(<<<SQL SELECT EXTRACT(YEAR_MONTH FROM FROM_UNIXTIME(`Date`)) AS year_mo, `Name` AS name, SUM(`Apples`) AS sum_apples FROM apples_table GROUP BY 1,2 ORDER BY 1,3 DESC; SQL ) or die(mysql_error()); $last_year_mo = ''; $same_date_count = 0; while ($row = mysql_fetch_assoc($query)) {
source share