I wrote a query to get month-wise record in user table as follows
SELECT COUNT( `userID` ) AS total, DATE_FORMAT( `userRegistredDate` , '%b' ) AS
MONTH , YEAR( `userRegistredDate` ) AS year
FROM `users`
GROUP BY DATE_FORMAT( FROM_UNIXTIME( `userRegistredDate` , '%b' ) )
Output:
total MONTH year
---------------------------
3 May 2013
2 Jul 2013
--------------------------
Expected Output:
total MONTH year
---------------------------
0 Jan 2013
0 Feb 2013
0 Mar 2013
0 Apr 2013
3 May 2013
0 Jun 2013
2 Jul 2013
--------------------------
I need to show the record even if data not exist. How to do this?
I won't say much about efficiency as I have not tested it against other methods but without having a temp table this seem a fair way to go.
If you make the union based on a date format you can even reduce the work and load on the query.
Live DEMO of both queries.
You may need a table to hold every "month" record. A temp table can do the trick:
And now, you can left join your data with this newly created temp table:
Notice that you can put the temp table creation (and fill) in a stored procedure.
I use
last_day
for simplicity, but you are free to use any date in the month that you like, if you join it correctly.Hope this helps