Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 Sum Product of two fields

I need to calculate the sum of the product of two fields in my Rails 3 app (i.e. the equivalent to Excel's sumproduct function). Is there a method in Rails that will help with this and if not, then what would be the rails code using custom sql?

For example, a Hotel has many Rooms. A Room has attributes of sqft (square feet), quantity (of that size) and hotel_id. I would like to calculate the total sqft of all the Rooms in a given Hotel. In SQL, for a Hotel.id = 8, I believe the following statement will work:

select sum(rooms.sqft * rooms.quantity) as SumSqft from rooms inner join hotels on rooms.hotel_id = hotels.id where hotels.id = 8;
like image 884
Ryan Avatar asked Apr 08 '13 20:04

Ryan


1 Answers

Yep :

Room.where(hotel_id: 8).sum("sqft * quantity")
like image 107
Anthony Alberto Avatar answered Sep 30 '22 14:09

Anthony Alberto