Rails 的新手,但我找不到这个功能!
假设您有一组发票,其中包括 ID、公司名称和发票总额。出于某种原因,有多家公司同名。您想要创建一个 1xn 矩阵,其中每一行都包含具有唯一公司名称的公司数据。
如何将名称相同的公司组合在一起,并将它们的发票总额加在一起。您不关心将哪个 id 保存到该行。 Group+Map是唯一的方式吗?
例如
[1523, 'Red Roses Inc', 1300.00],
[4126, 'Blue Birds LLC', 110.00],
[846, 'Red Roses Inc', 400.00],
成为
[1523, 'Red Roses Inc', 1700.00],
[846, 'Blue Birds LLC', 110.00],
最佳答案
如果公司和发票在一个表中例如你的模型是发票
Invoice.group(:company_name).sum(:total)
# sample implementation how to get data and print the result
data_result = Invoice.group(:company_name).sum(:total)
data_result.each do |v|
puts "company #{v[0]} total number #{v[1]}"
end
# this will print
# company Red Roses Inc total number 1700
# company Blue Birds LLC total number 110
关于mysql - Rails 组收集并对某些字段求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54220654/