Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 831
Serge Vinogradoff Avatar asked Dec 18 '25 14:12

Serge Vinogradoff


1 Answers

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)
like image 156
pozs Avatar answered Dec 21 '25 06:12

pozs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!