I’m trying to count how many result in each month.
This is my query :
SELECT
COUNT(*) as nb,
CONCAT(MONTH(t.date),0x3a,YEAR(t.date)) as period
FROM table1 t
WHERE t.criteria = 'value'
GROUP BY MONTH(t.date)
ORDER BY YEAR(t.date)
My Result:
nb period
---------------
7 6:2009
46 8:2009
2 10:2009
1 11:2009
14 1:2009
9 9:2010
161 7:2010
5 2:2010
88 3:2010
28 4:2010
4 5:2011
2 12:2011
The problem is, I’m sure that I’ve result between 5:2011 & 12:2011 , and each other period
since 2009 … :/
This is a problem of my request or mysql configuration ?
Thx a lot
You have to group by both the year and the month. Otherwise your April 2012 rows are grouped with April 2011 (and April 2010 …) rows as well.
(and is there a reason you used
0x3aand not':'?)You could also use some other DATE and TIME functions of MySQL so there are fewer functions calls per row and probably a more efficient query:
For several queries, it’s useful to have a permanent Calendar table in your database (with all dates or all year-months) or even several Calendar tables. Example:
Those can also help us make the one we’ll need here:
Then you can use the Calendar tables to write more complex queries, like the variation you want (with missing months) and probably more efficiently. Tested in SQL-Fiddle: