【问题标题】:How to group and sum all currencies如何对所有货币进行分组和求和
【发布时间】:2017-07-25 14:32:10
【问题描述】:

我希望标题是正确的。我需要汇总所有货币,即所有美元、英镑等,但不要将所有货币合并为一个总和。

基本上,如果我有 2x $4 和 3x £10,那将是 $8£30

我有一个Income 模型,其属性为:currency(字符串)和:amount(浮点数):

我有什么工作,但我觉得它可以重构一点:

Income.all.group(:currency).count.map do |k,v|
  Income.where(currency: k).map.sum(&:amount)
end

这给了我一个总数的数组。好的。我需要一种更好的格式,例如 Hash:

{
  USD => 8.0,
  GBP => 30.0
}

可能吗?请问怎么样?

【问题讨论】:

    标签: ruby-on-rails ruby activerecord ruby-on-rails-5


    【解决方案1】:

    我认为以下方法可以:

    Income.group(:currency).sum(:amount)
    

    SQL 看起来像:

    SELECT SUM(income.amount) AS sum_amount, currency AS currency
      FROM income
      GROUP BY income.currency
    

    【讨论】:

    • 天啊!这么简单?谢谢
    猜你喜欢
    • 1970-01-01
    • 2015-09-09
    • 1970-01-01
    • 1970-01-01
    • 2015-06-04
    • 2022-07-12
    • 2019-01-25
    • 2015-05-17
    • 1970-01-01
    相关资源
    最近更新 更多