Rails 3 Sum 两个字段的乘积 [英] Rails 3 Sum Product of two fields

查看:26
本文介绍了Rails 3 Sum 两个字段的乘积的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要计算 Rails 3 应用程序中两个字段的乘积之和(即等效于 Excel 的 sumproduct 函数).Rails 中是否有一种方法可以帮助解决这个问题,如果没有,那么使用自定义 sql 的 Rails 代码是什么?

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?

例如,一家酒店有许多房间.房间具有 sqft(平方英尺)、数量(该大小)和 hotel_id 的属性.我想计算给定酒店中所有房间的总平方英尺.在 SQL 中,对于 Hotel.id = 8,我相信以下语句会起作用:

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;

推荐答案

是的:

Room.where(hotel_id: 8).sum("sqft * quantity")

这篇关于Rails 3 Sum 两个字段的乘积的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆