How to make a query in Postgres to group records by month they were created? (:created_at datetime column)

▼魔方 西西 提交于 2020-01-03 05:25:06

问题


I have this Ruby code:

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 is just a scope:

scope :created_on_month, -> (month = Time.now) { where{ (created_at >= month.beginning_of_month) & (created_at <= month.end_of_month) } } 

created_at is just a standard datetime timestamp.

How can I optimize it to make one query instead of 12?

I saw some people use GROUP_BY, but I'm not that good with PostgreSQL to be able to build such query myself. The query should group records by month of the year and return count. Maybe someone could help me out. Thanks.


回答1:


Use the date_trunc() function in your GROUP BY clause, if you want to group by each month of each year:

GROUP BY date_trunc('month', created_at)

Use EXTRACT() function in your GROUP BY clause, if you want to group by each month in every year:

GROUP BY EXTRACT(MONTH FROM created_at)


来源:https://stackoverflow.com/questions/23757803/how-to-make-a-query-in-postgres-to-group-records-by-month-they-were-created-c

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