簡體   English   中英

如何在Rails中編寫以下查詢?

[英]How can I write the following query in Rails?

我需要編寫一個查詢,該查詢僅統計以前未參加活動的個人。

這是模型

class Individual < ActiveRecord::Base
  has_many :attendances, dependent: :destroy
  has_many :events, through: :attendances
end

class Attendance < ActiveRecord::Base
  belongs_to :event
  belongs_to :individual
end 

class Event < ActiveRecord::Base
  has_many :attendances, dependent: :destroy
  has_many :individuals, through: :attendances
end

我認為我有2個不同的查詢。 每個查詢都會評估每個會計年度的事件出席率。

2015財年查詢:

  <%= Event.published.joins( :attendances => :individual ).where( 
  :events => {:fiscal_session => "2014-10-01".."2015-09-30"}
  ).distinct.count(:individual_id) %>

查詢2016財年:

  <%= Event.published.joins( :attendances => :individual ).where( 
  :events => { :fiscal_session => "2015-10-01".."2016-09-30"}
  ).distinct.count(:individual_id) %>

問題在於,對於2016財年的查詢不會忽略參加2015財年活動的個人。

我使用的是postgresql,我嘗試編寫范圍和幫助程序方法,以過濾掉2015財年參加的個人。但是我只是無法弄清楚。

例如,這是2015財年:

<%= Individual.joins(attendances: :event).where( 
:events => {:fiscal_session => "2014-10-01".."2015-09-30"}
).group('individuals.id').having('count(attendances.id) > 0').count %>

結果是:

{2787=>1, 3469=>1} 

這是2016財年

<%= Individual.joins(attendances: :event).where( 
:events => {:fiscal_session => "2015-10-01".."2016-09-30"}
).group('individuals.id').having('count(attendances.id) > 0').count %>

結果是這樣的:

{2905=>1, 3444=>1, 2787=>1, 2790=>1, 2858=>1} 

如您所見, individual_id 2787被計數兩次。 我不想在2016財年的查詢中計入2787

用Rails和ActiveRecord實現所需計數的正確方法是什么?

我認為完成您想要做的事情的最佳方法是使用兩個查詢。

ignore_individuals = Event
.published
.joins(attendances: :individual)
.where( 
  'events.fiscal_session <= ?', '2015-09-30'
)
.pluck(:individual_id)

Event
.published
.joins(attendances: :individual)
.where.not(individual_id: ignore_individuals)
.where( 
  events: { fiscal_session: "2015-10-01".."2016-09-30" }
).distinct.count(:individual_id)

我認為您正在尋找: Individual.includes(:events).where( events: { id: nil } ).count

這些人從未參加過任何活動。

不太樂觀,但是如果您正在尋找參加2016年某項活動的個人人數,並且您的餐桌上有時間戳記,我相信您可以做到

Individual.joins(:attendances).where("attendances.created_at > ?", "01-01-2016").count

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM