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条回答
Emotional °昔
2楼-- · 2019-01-04 00:49

I prefer

SELECT
    MONTHNAME(t.summaryDateTime) as month, YEAR(t.summaryDateTime) as year
FROM
    trading_summary t 
GROUP BY EXTRACT(YEAR_MONTH FROM t.summaryDateTime) DESC";
查看更多
虎瘦雄心在
3楼-- · 2019-01-04 00:50
SELECT MONTHNAME(t.summaryDateTime) as month, YEAR(t.summaryDateTime) as year
FROM trading_summary t
GROUP BY YEAR(t.summaryDateTime) DESC, MONTH(t.summaryDateTime) DESC

Should use DESC for both YEAR and Month to get correct order.

查看更多
做自己的国王
4楼-- · 2019-01-04 00:55
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()

查看更多
干净又极端
5楼-- · 2019-01-04 00:56

use EXTRACT function like this

mysql> SELECT EXTRACT(YEAR FROM '2009-07-02');
       -> 2009
查看更多
做自己的国王
6楼-- · 2019-01-04 00:59
GROUP BY DATE_FORMAT(summaryDateTime,'%Y-%m')
查看更多
登录 后发表回答