我正在将手动 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