I have the following set of data:
ID | CREATED | USER
--------------------------
1 | 2012-01-14 | XYZ
2 | 2012-03-14 | XYZ
3 | 2012-03-15 | XYZ
4 | 2012-03-24 | ABC
5 | 2012-04-10 | XYZ
6 | 2012-04-11 | ABC
And I need a report that shows the COUNT for a given user but also with a 0 for months where there are no records.
MTH | COUNT
-------------
JAN | 1
FEB | 0
MAR | 2
APR | 1
I managed to get it to work but without the 0 for months with no records. So far, I have this syntax which is throwing an error..
SELECT Month(CREATED), COUNT(SELECT * FROM SEARCHES WHERE USER = 'XYZ')
FROM SEARCHES
GROUP BY Month(CREATED)
Here is general query for grouping by date range. @startDate and @endDate define the range; you might set min(created) and max(created) for user, or some fixed range.
CTE monthlyRange generates table of months – first of current month, first of next month. Searches is later left-joined to monthlyRanges by created. Note that user is filtered in join as this is left join and filtering in where clause would effectively turn it into inner join.
Here is Sql Fiddle for testing