gpt4 book ai didi

ruby-on-rails - 如何对所有货币进行分组和求和

转载 作者:数据小太阳 更新时间:2023-10-29 08:58:31 25 4
gpt4 key购买 nike

我希望标题是正确的。我需要对所有货币求和,即所有 $、£ 等,但不要将所有货币合并为一个总和。

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

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

我的作品有效,但我觉得它可以重构一下:

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

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

{
USD => 8.0,
GBP => 30.0
}

可能吗?请问怎么办?

最佳答案

我认为以下会做:

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

SQL 看起来像:

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

关于ruby-on-rails - 如何对所有货币进行分组和求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42613475/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com