title: How to make a query in Postgres to group records by month they were created? (:created_at datetime column)
body: <p>I have this Ruby code:</p>
  
  <pre><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
  </code></pre>
  
  <p>CreatedOnMonth is just a scope:</p>
  
  <pre><code>scope :created_on_month, -&gt; (month = Time.now) { where{ (created_at &gt;= month.beginning_of_month) &amp; (created_at &lt;= month.end_of_month) } } 
  </code></pre>
  
  <p><code>created_at</code> is just a standard datetime timestamp.</p>
  
  <p>How can I optimize it to make one query instead of 12? </p>
  
  <p>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.</p>