How to: group by month with SQL

Posted by AngelEyes on Geeks with Blogs See other posts from Geeks with Blogs or by AngelEyes
Published on Thu, 17 Jun 2010 08:14:37 GMT Indexed on 2010/06/17 7:33 UTC
Read the original article Hit count: 445

Filed under:

I took this particular code from http://weblogs.sqlteam.com/jeffs/archive/2007/09/10/group-by-month-sql.aspx,

a good read. Shows you what to avoid and why.

 

The recommended technique is the following:

 

GROUP BY dateadd(month, datediff(month, 0, SomeDate),0)

 

By the way, in the "select" clause, you can use the following:

 

SELECT

        month(dateadd(month, datediff(month, 0, SomeDate),0)) as [month],

        year(dateadd(month, datediff(month, 0, SomeDate),0)) as [year],

 

Just remember to also sort properly if needed:

 

ORDER BY dateadd(month, datediff(month, 0, SomeDate),0)

© Geeks with Blogs or respective owner