1

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!

2
  • will you please able to specify your table structure in details? Commented Sep 26, 2012 at 3:23
  • 2
    Why would you expect a result for a row that does not exist - try left joining against a table that has all the months Commented Sep 26, 2012 at 3:26

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

i suggest everyone have a numbers table or tvf available for uses like this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.