Search code examples
mysqlsqlgroup-bydatetime-generation

selecting between date range and forcing empty rows to be 0?


I have a table that looks like

expires    | value  
-------------------
2011-06-15 | 15  
2011-06-15 | 15  
2011-06-25 | 15  
2011-07-15 | 15  
2011-07-15 | 15  
2011-07-25 | 15  
2011-08-15 | 15  
2011-08-15 | 15  
2011-08-25 | 15

I want to run a query that will spit out

June   | 45  
July   | 45  
August | 45  

So my query is

  SELECT SUM(amount) AS `amount`, 
         DATE_FORMAT(expires , '%M') AS `month`  
    FROM dealDollars 
   WHERE DATE(expires) BETWEEN DATE(NOW()) 
                           AND LAST_DAY(DATE(NOW()+INTERVAL 3 MONTH)) 
GROUP BY MONTH(expires)

Which works fine. But with the result, if there were no rows in say July, July would not show up.

How can I force July to show up with 0 as its value?


Solution

  • There is no easy way to do this. One possible way is to have a table called months: Which will have 12 rows: (January, February, ..., December)

    You can left join the Months table with the query you have to get the desired output.