简体   繁体   中英

How to group by day and year in Active Record in Rails3

I'm trying to recreate the following mysql query in rails 3

 select count(id), year(created_at), month(created_at) from table where published_state = 'published' group by year(created_at), month(created_at);

I've tried something like:

results = Table.select('count(id), year(created_at), month(created_at)').where('published_state LIKE ?', 'published').group('year(created_at), month(created_at)')

but it doesn't return what I want.

I just get this in return

[#<Table >, #<Table >, #<Table >, #<Table >, #<Table >, #<Table >,
 #<Table >, #<Table >, #<Table >, #<Table >, #<Table >, #<Table >, #<Table >, #<Table >, #<Table >, #<Table >, #<Table >]

How can I accomplish this?

Thanks!

Try this:

Table.where(:published_state => 'published').
  group('year(created_at)').group('month(created_at)').count(:id)

The format of the results is not quite what I was expecting (it's a hash with array keys like [year, month] and count values) but maybe it will serve your purposes?

If you're using PostgreSQL, you can also use the date_trunc function (splitting lines for readability but probably won't work in real Ruby):

Table.select('count(id), date_trunc('month', created_at) as month')
  .where('published_state LIKE ?', 'published').group('month')

Basically, it truncates or cuts off the parts of the date that are no longer significant. For example, if you choose 'month', it still preserves the year with the month but not the day and time.

I would probably also order it like so:

Table.select('count(id), date_trunc('month', created_at) as month')
  .where('published_state LIKE ?', 'published').group('month')
  .order('month' DESC)
  .limit(24)

Read more in the docs here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM