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;
Yep :
Room.where(hotel_id: 8).sum("sqft * quantity")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With