I have two tables, fbpost and fbalbum, which each have a DATETIME column called createdTime. I’m finding the number of albums per month, and the number of posts per month, and adding them together.
Here’s my query(which works as described):
SELECT createdTime, itemCount FROM
(SELECT DATE_FORMAT(createdTime, '%m-%Y') AS createdTime, COUNT(*) AS itemCount FROM fbpost WHERE page_id =2
GROUP BY YEAR(createdTime), MONTH(createdTime)
UNION ALL
SELECT DATE_FORMAT(createdTime, '%m-%Y') AS createdTime, COUNT(*) AS itemCount FROM fbalbum WHERE page_id=2
GROUP BY YEAR(createdTime), MONTH(createdTime)) AS foo
GROUP BY createdTime
This gives the results:
01-2009 | 173
01-2010 | 21
01-2011 | 521
01-2012 | 776
02-2009 | 117
02-2010 | 158
02-2011 | 678
...
But I would like the results to be ordered like this:
01-2009 | 173
02-2009 | 56
03-2009 | 543
04-2009 | 211
05-2009 | 723
06-2009 | 55
07-2009 | 521
...
How can I achieve this?
Note: DATE_FORMAT() gives a string, not a DATETIME, so you can’t sort by date. But, if I take out the DATE_FORMAT() in the two nested select statements, I get 2 rows for most months, since that would leave the day. Though there would be only one row per month for each nested select, they day would usually differ, since the last item in a month may be on any day.
Don’t use
DATE_FORMATuntil your outer query:See it in action *
*Demo does not have
page_id