如何在Postgres的Rails中按天分组和计数? [英] How to group and count by day in Rails in Postgres?
问题描述
这样的问题如何按天分组而不是按日分组日期?显示了如何在Ruby中进行分组。
This SO question How do I group by day instead of date? shows how to group in Ruby.
此方法有效,但对于大量记录而言将非常慢。
如何做到在Postgres中按天进行:created_at
的分组和计数?
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?
推荐答案
如果尚未定义订单范围,则可以使用postgres中的 date()
方法,如下所示:
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")
如果您有订单范围:
Post.all.except(:order).
select("date(created_at) as created_date").group("created_date")
您必须定义选择字段才能进行自定义分组,因此 select()
部分应包含您需要记录集包含的字段。
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.
这篇关于如何在Postgres的Rails中按天分组和计数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!