Rails 中相乘列的总和
这应该很容易。在 MySQL 中我可以这样做:
select sum(column1*column2) as sum1 from table
How do you do this in Rails with sqlite?我已经尝试过 find_by_sql 与上面的确切查询,以及 find(:all, :select=>...) 和各种其他东西,但没有一个返回正确的值。大多数都是空白的,就像这样:
[#<Element> ]
我可以循环遍历,取出值,然后求和,但必须这样做似乎很荒谬。
有人能指出我明显缺少的东西吗?谢谢!
This should be easy. In MySQL I could just do:
select sum(column1*column2) as sum1 from table
How do you do this in Rails with sqlite? I've tried find_by_sql with the exact query above, as well as find(:all, :select=>...), and all sorts of other things, but none return the proper value. Most are just blank, like this:
[#<Element> ]
I could loop through, pull out values, and then sum, but it seems absurd to have to do that.
Can someone point me to what I'm obviously missing? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
http://ar.rubyonrails.org/classes/ActiveRecord/Calculations/ClassMethods.html
http://ar.rubyonrails.org/classes/ActiveRecord/Calculations/ClassMethods.html
正如 @glortho 在评论中所说,解决方案是
Element.sum( "column1*column2" )
这甚至可以跨多个表使用
Foo.includes(:bars).references(:bars) .sum('foos.cost * Bars.available')
SQL 令人难以置信!
As @glortho said in a comment, the solution is
Element.sum( "column1*column2" )
This even works across multiple tables
Foo.includes(:bars).references(:bars).sum('foos.cost * bars.available')
SQL IS INCREDIBLE!