在多个表上选择日期范围内的计数

时间:2015-03-17 19:18:40

标签: sql ruby-on-rails activerecord class-method

我需要一个范围,可以在侦听,下载和购买的日期范围内获取计数。 我可以在一个范围内执行此操作吗?

我有这个Rails范围,可以让我在一定范围内听到顶级曲目。

scope :top_by_listens, lambda{|count=nil, range_start=nil, range_end=nil|
    joins(:listens)
      .group('tracks.id')
      .select("tracks.*, count(user_actions.id) AS action_count")
      .where('user_actions.created_at between ? and ?', range_start || Time.now.beginning_of_month, range_end || Time.now.end_of_month)
      .order("action_count DESC")
      .limit(count || 5)
  }

我可以打电话给" action_count"在轨道上并获得指定范围内的计数。

我希望能够调用类似" track.listens.action_count"和" track.downloads.action_count"。

我知道我可以加入joins(:listens, :downloads, :orders)之类的倍数,但我怎样才能调用' action_count'在三个不同的实体?

这是开始:

 scope :top_by_all, lambda{|count=nil, range_start=nil, range_end=nil|
    joins(:listens, :downloads, :orders)
      .group('tracks.id')
      .select("tracks.*, count(user_actions.id) AS action_count")
      .where('user_actions.created_at between ? and ?', range_start || Time.now.beginning_of_month, range_end || Time.now.end_of_month)
      .order("action_count DESC")
      .limit(count || 5)
  }

任何帮助/想法都赞赏!

1 个答案:

答案 0 :(得分:1)

我还没有验证你的where子句和限制是否按预期工作,但这里是一个如何在单个查询中解决问题的示例。我认为它也会很快。

scope :top_by_all, lambda{|count=nil, range_start=nil, range_end=nil|
  joins(:listens, :downloads, :orders)
    .group('tracks.id')
    .select("tracks.*, count(Distinct listens.id) + count(Distinct downloads.id) + count(Distinct orders.id) as action_count")
    .where('user_actions.created_at between ? and ?', range_start || Time.now.beginning_of_month, range_end || Time.now.end_of_month)
    .order("action_count DESC")
    .limit(count || 5)
}