How to group and count by day in Rails in Postgres?

元气小坏坏 提交于 2019-12-22 12:47:26

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!