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

Submitted by ionut on 29/08/2011

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.



Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.