Home » Mysql » Group by month and year in MySQL

Group by month and year in MySQL

Posted by: admin November 1, 2017 Leave a comment

Questions:

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.

Answers:
GROUP BY YEAR(t.summaryDateTime), MONTH(t.summaryDateTime) DESC;

is what you want.

Questions:
Answers:
GROUP BY DATE_FORMAT(summaryDateTime,'%Y-%m')

Questions:
Answers:
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.

Questions:
Answers:

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";

Questions:
Answers:

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

Questions:
Answers:

use EXTRACT function like this

mysql> SELECT EXTRACT(YEAR FROM '2009-07-02');
       -> 2009

Questions:
Answers:

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

Questions:
Answers:
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()

Questions:
Answers:

Use

GROUP BY year, month DESC";

Instead of

GROUP BY MONTH(t.summaryDateTime) DESC";