ActiveRecord子查询比较作为范围

时间:2012-09-21 00:56:10

标签: sql ruby-on-rails sql-server activerecord

我正在将手动SQL查询重写为ActiveRecord查询,以便在Rails应用程序中使用。

它的作用是从同一个表中收集两组用户:1在上周有一个合格事件(44或48),以及一个月前有相同资格事件的用户组。

这是当前查询。我不知道如何将其变成ActiveRecord范围:

select top 500 active_users_last_week.email 
    from (
      select distinct(email) from user_event_tracking
      where event_id in (44,48)
      and sitedb_created_date between getdate()-8 and getdate()-1
      and sitedb_name = 'XYZ'
      and email not like '%@company.com'
      and email not like '%@other_company.com'
    ) active_users_last_week, 
    (
      select distinct(email) from user_event_tracking
      where event_id in (44,48)
      and sitedb_created_date between getdate()-60 and getdate()-30
      and sitedb_name = 'XYZ'
      and email not like '%@company.com'
      and email not like '%@other_company.com
    ) active_users_last_month
where active_users_last_week.email = active_users_last_month.email;

有关如何将其转换为ActiveRecord范围的任何建议?我已将这些设置为范围:

scope :active_events, lambda {
    where("event_id in (44,48)")
}

scope :for_property, lambda { |property| 
    where('sitedb_name = ?', property)
}

scope :last_week, lambda {
    where("sitedb_created_date between GETDATE()-8 and GETDATE()-1")
}

scope :last_month, lambda {
    where("sitedb_created_date between GETDATE()-60 and GETDATE()-30")
}

scope :no_test_users, lambda {
    where("email not like '%@company.com' and email not like '%@other_company.com'")
}

范围都是单独工作(和相互配合)。问题是如何以有效的方式获取Event.active_events.last_weekEvent.active_events.last_month中的电子邮件。

1 个答案:

答案 0 :(得分:1)

试试这个:

Event.select(:email).where(:event_id => [44,48], sitedb_created_date => (8.days.ago..1.day.ago), :sitedb_name => 'XYZ', :email => Event.select(:email).where(:event_id => [44,48], sitedb_created_date => (60.days.ago..30.days.ago), :sitedb_name => 'XYZ').where(Event.arel_table[:email].does_not_match_all(["%company.com","%other_company.com"])))

您可能需要修补几天将其调整到您的日期范围,我不是100%确定它们是否具有包容性。您可能需要将8.days.ago更改为7.days.ago等。

您也应该可以使用范围执行此操作:

Event.active_events.last_week.where(:email => Event.active_events.last_month.select(:email))