ruby on rails - ActiveRecord query that groups by ID and sums rows -
my postgresql db has structure:
table orders id (string) userid (string) prodid (string) value (integer)
this example of data:
id userid prodid value 1 a@a.aaa prod1 5 2 b@b.bbb prod1 -1 3 a@a.aaa prod1 -4 4 a@a.aaa prod2 9
i want query activerecord sums values specific userid
, query (a@a.aaa) return list this:
prod1 1 prod2 9
my first approach one, doesn't work:
orderlist = orders.select("sum(orders.amount) num_prods").where((:userid => here_user_id).group(:prodid)
edit: rephrased feedback
order.where(userid: id).group(:prodid).sum(:value) # replace `:id` value
this should give hash, so
{1=>10, 2=>20, 5=>20}
the keys 1,2,5
represent product id, , values 10,20,20
represent sum values.
Comments
Post a Comment