Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I group by two columns and provide a sum of the grouped items

I'm building an inventory database and it has 2 columns that I would like to group by (manufacturer and model). How would I group by these columns and provide a sum of the items group?

For example:

Qty  Manufacturer  Model
1    Sony          MF-2002
1    Sony          MF-2002
1    Planar        PL2410W
1    Planar        PL2410W
1    Planar        PL2410W
1    Planar        PL3610D
1    Planar        PL3610D

Result:

Qty  Manufacturer  Model
2    Sony          MF-2002
3    Planar        PL2410W
2    Planar        PL3610D
like image 438
Jason Stokes Avatar asked Feb 20 '13 13:02

Jason Stokes


1 Answers

Assuming an Item model, you can pass an array to the group method as follows:

Item.group(["manufacturer", "model"]).sum(:qty)
# => {["Planar", "PL2410W"]=>3, ["Planar", "PL3610D"]=>2, ["Sony", "MF-2002"]=>2}
like image 147
Dylan Markow Avatar answered Sep 28 '22 09:09

Dylan Markow