Selecting data from an SQL table and group it by month when having a date field

This is an example of an SQL query that allow you to select (and sum) the fields of a table and grouping it by month (supposing there is a date field)

 

SELECT DATEPART(yyyy, [the_date_field]) AS year, DATEPART(MM, [the_date_field]) AS month, SUM([random_field]) AS total FROM [table_name] WHERE [condition] GROUP BY DATEPART(yyyy, [the_date_field]), DATEPART(MM, [the_date_field]) ORDER BY DATEPART(yyyy, [the_date_field]), DATEPART(MM, [the_date_field]) ASC

 

This query was tested on MSSQL SERVER but it can be easely adapted for MySQL.