问题
This SO question How do I group by day instead of date? shows how to group in Ruby.
This works, but is going to be very slow for a large number of records.
How to do it so that the grouping and counting by :created_at by day happens within Postgres?
回答1:
If you haven't an order scope defined, you can use date() method from postgres, like this:
Post.select("date(created_at) as created_date").group("created_date")
And if you do have an order scope:
Post.all.except(:order).
select("date(created_at) as created_date").group("created_date")
You will have to define select fields in order to have a custom grouping, so the select() part should contain the fields you need your recordset to contain.
来源:https://stackoverflow.com/questions/29834995/how-to-group-and-count-by-day-in-rails-in-postgres