samedi 25 avril 2015

ActiveRecord query that groups by ID and sums rows

My Postgresql DB has this structure:

TABLE Orders
id (string)
userId (string)
value (integer)

This is an example of data:

id      userId      value
1       a@a.aaa     5
2       b@b.bbb     -1
3       a@a.aaa     -4
4       b@b.bbb     9

I want to do a query from ActiveRecord that sums all the values for a specific userId, like this:

a@a.aaa    1

My first approach is this one, but it doesn't work:

orders = Orders.where((:username => HERE_THE_USER_ID).sum(value)

Aucun commentaire:

Enregistrer un commentaire