2012-09-21 98 views
0

我正在將一個手動SQL查詢重寫爲ActiveRecord查詢以用於Rails應用程序。ActiveRecord子查詢比較作爲範圍

它做了什麼它收集了來自同一個表的兩組用戶: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中的電子郵件。

+0

看起來它返回上週僅供網友如果他們在上個月還有資格賽。那是對的嗎?什麼是型號名稱? – iouri

+0

是的,這是完全正確的。該模型被命名爲Event。 –

+0

還有一個用戶模型?他們如何加入?通過電子郵件? – iouri

回答

0

試試這個:

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)) 
+0

60和30被顛倒,答案更新。 – iouri

+0

太棒了。這很好。感謝你的回答! –