I am listing all the news articles by month, and year, and how many articles occured during that month...
However I noticed that in the new year it is sorting by month only and not
Here is my SQL
$archive1_sql = "SELECT YEAR(`ndate`) AS 'year', MONTH(`ndate`) AS 'month', COUNT(`nid`) AS 'count' FROM `weaponsnews` GROUP BY YEAR(`ndate`), MONTH(`ndate`) DESC";
And it returns
December 2012 (1)
November 2012 (11)
October 2012 (6)
September 2012 (8)
August 2012 (16)
July 2012 (8)
June 2012 (6)
May 2012 (12)
April 2012 (4)
March 2012 (2)
February 2012 (4)
January 2013 (1)
What I want it to do is sort like this
January 2013 (1)
December 2012 (1)
November 2012 (11)
October 2012 (6)
September 2012 (8)
August 2012 (16)
July 2012 (8)
June 2012 (6)
May 2012 (12)
April 2012 (4)
March 2012 (2)
February 2012 (4)
How do I do that?
Add DESC with YEAR too
SELECT
YEAR(`ndate`) AS 'year',
MONTH(`ndate`) AS 'month',
COUNT(`nid`) AS 'count'
FROM `weaponsnews`
GROUP BY YEAR(`ndate`) , MONTH(`ndate`)
ORDER BY YEAR(`ndate`) DESC , MONTH(`ndate`) DESC
Change the GROUP BY
to:
GROUP BY YEAR(`ndate`) DESC,
MONTH(`ndate`) DESC
If there is no ORDER BY
, MySQL has an (non-standard SQL) feature that it orders the results according to the GROUP BY
ordering. It also allows the ASC
and DESC
keywords there.
From MySQL docs SELECT
syntax:
If you use
GROUP BY
, output rows are sorted according to theGROUP BY
columns as if you had anORDER BY
for the same columns. To avoid the overhead of sorting thatGROUP BY
produces, addORDER BY NULL
:SELECT a, COUNT(b) FROM test_table GROUP BY a ORDER BY NULL;
MySQL extends the
GROUP BY
clause so that you can also specifyASC
andDESC
after columns named in the clause:SELECT a, COUNT(b) FROM test_table GROUP BY a DESC;
To get your records in (reversed) chronological order, use "order by ndate DESC":
SELECT
YEAR(`ndate`) AS 'year',
MONTH(`ndate`) AS 'month',
COUNT(`nid`) AS 'count'
FROM `weaponsnews`
GROUP BY YEAR(`ndate`) , MONTH(`ndate`)
ORDER BY ndate DESC
Then you can group by whatever you want (days, weeks...), you do not need to change your 'order by' statement.