1

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

它的作用是从同一张表中收集两组用户:一组在上周有合格事件(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_week获取电子邮件。Event.active_events.last_month

4

1 回答 1

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))
于 2012-09-21T01:48:30.933 回答