Group by month and year in MySQL

Derek Adair picture Derek Adair · Jul 29, 2010 · Viewed 142.4k times · Source

Given a table with a timestamp on each row, how would you format the query to fit into this specific json object format.

I am trying to organize a json object into years / months.

json to base the query off:

{
  "2009":["August","July","September"],
  "2010":["January", "February", "October"]
}

Here is the query I have so far -

SELECT
    MONTHNAME(t.summaryDateTime) as month, YEAR(t.summaryDateTime) as year
FROM
    trading_summary t 
GROUP BY MONTH(t.summaryDateTime) DESC";

The query is breaking down because it is (predictably) lumping together the different years.

Answer

Mitch Dempsey picture Mitch Dempsey · Jul 29, 2010
GROUP BY YEAR(t.summaryDateTime), MONTH(t.summaryDateTime) DESC;

is what you want.