Hi there,
I have the following tables...
  User :has_many Purchases
  Item :has_many Purchases
...where Item has a column "amount" (can be + or -) and I need to find
all Users that have a positive SUM of "amounts" (over all Purchases
each
one has made).
How does this query look like? (I''m not sure how to handle
"SUM"
correctly, in this case.)
I started out with the following, but obviously, it''s wrong... (it
wouldn''t "include" Purchases that have an Item with a
negative
"amount"...)
  @users = User.find(:all,
                     :include => {:purchases => :item},
                     :select => "SUM(item.amount)",
                     :order => "...",
                     :conditions => "...",
                     :group => "users.id",
                     :having => "SUM(item.amount) > 0" )
Thanks for your help with this!
Tom
-- 
Posted via http://www.ruby-forum.com/.
-- 
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.
Tom Ha wrote:> Hi there, > > I have the following tables... > > User :has_many Purchases > Item :has_many Purchases > > > ...where Item has a column "amount" (can be + or -) and I need to find > all Users that have a positive SUM of "amounts" (over all Purchases each > one has made). > > How does this query look like? (I''m not sure how to handle "SUM" > correctly, in this case.)@user # assume this exists total = Purchase.sum(:amount, :conditions => { ''user_id'' => @user }) => SELECT sum("purchases".amount) AS sum_amount FROM "purchases" WHERE ("purchases"."user_id" = 1) -- Posted via http://www.ruby-forum.com/. -- 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.