hi, i have a sql statement which has a subquery on itself. it gets all the unique invitees of a given event from table invitation. i came up with the sql but i don''t know how to convert it into a named_scope which i can reuse in other places. please help. sql: select * from invitations inv join (select event_id, user_id, max(invite_time) as last_invite_time from invitations group by event_id, user_id) as last_inv on inv.event_id = last_inv.event_id and inv.user_id = last_inv.user_id and inv.invite_time = last_inv.last_invite_time and inv.event_id = @event_id thanks batterhead -- You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to rubyonrails-talk-/JYPxA39Uh5TLH3MbocFF+G/Ez6ZCGd0@public.gmane.org To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe-/JYPxA39Uh5TLH3MbocFF+G/Ez6ZCGd0@public.gmane.org For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.
Correct me if I''m wrong, but can''t that query be rewritten as follows: select event_id, user_id, max(invite_time) as last_invite_time from invitations where event_id = @event_id group by event_id, user_id Basically you want to get distinct event_id and user_id and the latest invite_time? No need to join to itself. In that case, you could go ahead and do it like this in ActiveRecord: Invitation.select("event_id, user_id, max(invite_time) as last_invite_time").group("event_id, user_id").where(:event_id => @event_id) -- You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to rubyonrails-talk-/JYPxA39Uh5TLH3MbocFF+G/Ez6ZCGd0@public.gmane.org To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe-/JYPxA39Uh5TLH3MbocFF+G/Ez6ZCGd0@public.gmane.org For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.