How to make a query in Postgres to group records by month they were created? (:created_at datetime column)
我有这个Ruby代码:
1 2 3 4 5 6 7 8 9 | def visits_chart_data(DOMAIN) last_12_months.collect do |MONTH| { created_at: MONTH, COUNT: DOMAIN.visits.created_on_month(MONTH).count } END END def last_12_months (0..11).to_a.reverse.collect{ |month_offset| month_offset.months.ago.beginning_of_month } END |
CreatedOnMonth只是一个范围:
1 | scope :created_on_month, -> (MONTH = TIME.now) { WHERE{ (created_at >= MONTH.beginning_of_month) & (created_at <= MONTH.end_of_month) } } |
如何优化它以进行一次查询而不是12?
我看到有些人使用GROUP_BY,但是我对PostgreSQL不太好,能够自己构建这样的查询。 查询应按年份对记录进行分组并返回计数。 也许有人可以帮助我。 谢谢。
如果要按每年的每个月分组,请使用
1 | GROUP BY date_trunc('month', created_at) |
如果您希望每年按月分组,请在
1 | GROUP BY EXTRACT(MONTH FROM created_at) |