David Undy
David Undy

Reputation: 953

Put empty spaces in an SQL select

I'm having difficulty creating a month->count select query in SQL.

Basically, I have a list of entries, all of which have a date associated with them. What I want the end result to be, is a list containing 12 rows (one for each month), and each row would contain the month number (1 for January, 2 for February, etc), and a count of how many entries had that month set as it's date. Something like this:

Month - Count
1     - 12
2     - 0
3     - 7
4     - 0
5     - 9
6     - 0

I can get an result containing months that have a count of higher than 0, but if the month contains no entries, the row isn't created. I get this result just by doing

SELECT Month(goalDate) as monthNumber, count(*) as monthCount 
FROM goalsList 
WHERE Year(goalDate) = 2012 
GROUP BY Month(goalDate) 
ORDER BY monthNumber

Thanks in advance for the help!

Upvotes: 1

Views: 120

Answers (1)

John Woo
John Woo

Reputation: 263893

Try something like this,

SELECT a.monthNo, COUNT(b.goalDate)
FROM (
        SELECT 1 monthNo UNION SELECT 2 monthNo
          UNION
        SELECT 3  monthNo UNION SELECT 4 monthNo
          UNION
        SELECT 5  monthNo UNION SELECT 6 monthNo
          UNION
        SELECT 7  monthNo UNION SELECT 8 monthNo
          UNION
        SELECT 9  monthNo UNION SELECT 10 monthNo
          UNION
        SELECT 11  monthNo UNION SELECT 12 monthNo
      )  a LEFT JOIN goalsList b
            ON a.monthNo = CAST(month(b.goalDate) as SIGNED)
GROUP BY a.monthNo
ORDER BY a.monthNo;

The idea was to create a list of records for month number in a temporary table and joins it with the table against goalsList. (Assuming that the OP doesn't have a table for month numbers)

SQLFiddle Demo

Upvotes: 2

Related Questions