views:

62

answers:

4

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.

A: 

Use

GROUP BY year, month DESC";

Instead of

GROUP BY MONTH(t.summaryDateTime) DESC";
Kyra
same result.....
Derek Adair
although it appears that GROUP BY MONTH(t.summaryDateTime) DESC doesn't order the months properly for some reason...
Derek Adair
oops sorry about that.
Kyra
+6  A: 
GROUP BY YEAR(t.summaryDateTime), MONTH(t.summaryDateTime) DESC";

Is what you want

webdestroya
this works. thank you very much!
Derek Adair
@Derek - no problem, happy to help
webdestroya
+1: Another alternative using [DATE_FORMAT](http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_date-format): `DATE_FORMAT(t.summaryDateTime, '%Y-%m')`
OMG Ponies
A: 

You are grouping by month only, you have to add YEAR() to the group by

eiefai
A: 
SELECT YEAR(t.summaryDateTime) as yr, GROUP_CONCAT(MONTHNAME(t.summaryDateTime)) AS month 
FROM trading_summary t GROUP BY yr

Still you would need to process it in external script to get exactly the structure you're looking for.

For example use PHP's explode to create an array from list of month names and then use json_encode()

Mchl