Group by month and year in MySQL

2019-01-04 00:35发布

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.

11条回答
家丑人穷心不美
2楼-- · 2019-01-04 00:39

You cal also do this

SELECT  SUM(amnt) `value`,DATE_FORMAT(dtrg,'%m-%y') AS label FROM rentpay GROUP BY YEAR(dtrg) DESC, MONTH(dtrg) DESC LIMIT 12

to order by year and month. Lets say you want to order from this year and this month all the way back to 12 month

查看更多
Animai°情兽
3楼-- · 2019-01-04 00:40

Use

GROUP BY year, month DESC";

Instead of

GROUP BY MONTH(t.summaryDateTime) DESC";
查看更多
劳资没心,怎么记你
4楼-- · 2019-01-04 00:41

I know this is an old question, but the following should work if you don't need the month name at the DB level:

  SELECT EXTRACT(YEAR_MONTH FROM summaryDateTime) summary_year_month 
    FROM trading_summary  
GROUP BY summary_year_month;

See EXTRACT function docs

You will probably find this to be better performing.. and if you are building a JSON object in the application layer, you can do the formatting/ordering as you run through the results.

N.B. I wasn't aware you could add DESC to a GROUP BY clause in MySQL, perhaps you are missing an ORDER BY clause:

  SELECT EXTRACT(YEAR_MONTH FROM summaryDateTime) summary_year_month 
    FROM trading_summary  
GROUP BY summary_year_month
ORDER BY summary_year_month DESC;
查看更多
再贱就再见
5楼-- · 2019-01-04 00:44

You must do something like this

SELECT onDay, id, 
sum(pxLow)/count(*),sum(pxLow),count(`*`),
CONCAT(YEAR(onDay),"-",MONTH(onDay)) as sdate 
FROM ... where stockParent_id =16120 group by sdate order by onDay
查看更多
家丑人穷心不美
6楼-- · 2019-01-04 00:48
GROUP BY YEAR(t.summaryDateTime), MONTH(t.summaryDateTime) DESC;

is what you want.

查看更多
劫难
7楼-- · 2019-01-04 00:48

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

查看更多
登录 后发表回答