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.
Refresh Type the characters you see in this picture. Type the characters you see in the picture; if you can't read them, submit the form and a new image will be generated. Not case sensitive.  Switch to audio verification.