Home >Database >Mysql Tutorial >How to Group MySQL Database Records by Month and Year?

How to Group MySQL Database Records by Month and Year?

Susan Sarandon
Susan SarandonOriginal
2025-01-03 20:03:40613browse

How to Group MySQL Database Records by Month and Year?

Group Database Records by Month and Year in MySQL

To organize a JSON object into years and months, you need a query that groups database records by both year and month.

Your query so far selects the month and year from the trading_summary table using the MONTHNAME() and YEAR() functions. However, it groups the results only by month, which lumps together records from different years.

To fix this, you need to add a second grouping clause using the YEAR() function:

GROUP BY YEAR(t.summaryDateTime), MONTH(t.summaryDateTime);

This will group the records by both year and month, giving you the desired JSON object format.

The above is the detailed content of How to Group MySQL Database Records by Month and Year?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn