Handy DQL: Count Objects by Month or Year

There are times when you want to count objects by month or year for a date attribute. The following DQL shows how to count objects of type dm_document by the month of their creation using the DATETOSTRING function.

select DATETOSTRING(r_creation_date, 'yy/mm') as period, count(*)
from dm_document
group by DATETOSTRING(r_creation_date, 'yy/mm')

You can add a where clause as usual if you want to add conditions to the query. You can also play with the date format but know that some format strings may not work as you might expect them to.

Advertisements

2 thoughts on “Handy DQL: Count Objects by Month or Year

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s