I’m rewriting a manual SQL query into an ActiveRecord query for use in a Rails app.
What it does it collect two groups of users from the same table: 1 who have a qualifying event (44 or 48) in the last week, and a group of users who have the same qualifying event a month ago.
This is the current query. I’m not sure how to turn this into an ActiveRecord scope:
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;
Any suggestions on how to turn this into an ActiveRecord scope? I have these set as scopes already:
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'")
}
The scopes all work individually (and with each other). The question is how to get emails that are in both Event.active_events.last_week and Event.active_events.last_month in an efficient way.
Try this:
You might need to tinker with days to adjust them to your date range, I am not 100% sure if they are inclusive or not. You might need to change 8.days.ago to 7.days.ago etc.
You also should be able to do this with your scopes: