Rails 中 ActiveRecord 中的多个 sum()
我想将多个 sum() 链接到一个组,同时选择其他字段。我还更喜欢使用 ActiveRecord 方法来执行此操作,而不是手动构造 sql 字符串,因为稍后我可能会修改 ActiveRecord 继承类的行为。
例如,我想
select user_id, sum(cost) as total_cost, sum(quantity) as total_quantity from line_items group by user_id
用以下内容来表示该语句(作为示例):
LineItem.select(:user_id).group(:user_id).sum(:cost).sum(:quantity)
原因是我稍后可能会添加额外的分组和 where 子句,所有总和将具有这些共同点。
I'd like to link multiple sums() to a single group by while selecting other fields at the same time. I'd also prefer to use the ActiveRecord methods to do this rather than construct a sql string manually, as I may modify the behavior of inherited classes of ActiveRecord later.
For example I'd like to represent the statement (as an example)
select user_id, sum(cost) as total_cost, sum(quantity) as total_quantity from line_items group by user_id
with something like:
LineItem.select(:user_id).group(:user_id).sum(:cost).sum(:quantity)
The reason being I may add additional group-bys and where-clauses later, which all the sums will have in common.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这对我有用:
我尝试了
sum(:cost, :quantity)
,但#sum
并不期望以这种方式定义参数。我也尝试了sum(:cost => :total_cost, :quantity => :total_quantity)
,但没有成功。This works for me:
I tried
sum(:cost, :quantity)
, but#sum
doesn't expect arguments defined this way. I also triedsum(:cost => :total_cost, :quantity => :total_quantity)
, to no avail.