Rails查询按日期范围分组

时间:2017-12-15 01:12:39

标签: sql ruby postgresql ruby-on-rails-4

我正在尝试按月过滤由过滤器限定的对象集。

当前数据库关联:

`Customer has_many Invoices and Invoice belongs to customers
 Store has_many customers and invoices`

在服务对象中调用它,返回满足特定条件的所有客户端

`store.new_clients_with_purchases_between("1/1/#{date.year}".to_date, 
"1/#{12}/#{date.year}".to_date.end_of_month)`

`new_clients_with_purchases_between` function is inside store model

`def new_clients_with_purchases_between(start_date, end_date)
    bw_customers.made_purchases_between(start_date, 
  end_date).where.not('bw_customers.id' => 
  customer_ids_with_purchases_before(start_date))
 end`

made_purchases_between函数位于Customer Model

`scope :made_purchases_between, -> (start_date, end_date) { 
joins(:bw_invoices).distinct.where('bw_invoices.purchase_date >= ? 
AND bw_invoices.purchase_date <= ? AND bw_invoices.subtotal > 0 AND 
bw_invoices.purchase_date < ?', start_date, end_date, Date.today) }`

我试图按月购买率对它们进行分组

`-----------------------------
[id][mon][year][numMon][count]
     jan   2017   1        10
     feb   2017   2        10`

依旧......

我当前的代码

`store.new_clients_with_purchases_between("1/1/#{date.year}".to_date, 
"1/#{12}/#    

{date.year}&#34; .to_date.end_of_month)。选择(&#34; purchase_date&#34;)。选择(&#39; purchase_date,COUNT(*)作为计数&#39;)。 (&#34; PURCHASE_DATE&#34;)`

给了我所有的purchase_date和计数,没有按月分组

有没有办法像上面那样完成一些?

非常感谢你的帮助

0 个答案:

没有答案