0

我有一个名为 Receipt 的模型,它具有以下内容:

  • date_of_purchase - 日期时间
  • total_value - 浮动

我有一个包含许多收据的数据库,例如:

收据 1

  • date_of_purchase = 2012-01-23
  • 总价值 = 6

收据 2

  • date_of_purchase = 2012-01-04
  • 总价值 = 70

收据 3

  • date_of_purchase = 2013-02-14
  • 总价值 = 1.23

收据 4

  • date_of_purchase = 2013-02-06
  • 总价值 = 90.34

...

收据 123

  • date_of_purchase = 2013-08-05
  • 总价值 = 43.69

我如何显示这样的东西:

{2012=>{1=>76}, 2013=>{2=>92.23, 3=> 34.43, ...}}

?

4

1 回答 1

1

以下应该工作

receipts = Receipt.find_by_sql("SELECT MONTH(date_of_purchase) AS month, 
                       YEAR(date_of_purchase) AS year, SUM(total_value) as sum
                       FROM receipts GROUP BY year, month")

receipts_hash = {}
receipts.each do |receipt|
  receipts_hash[receipt.year] = {} unless receipts_hash[receipt.year]
  receipts_hash[receipt.year][receipt.month] = receipt.sum
end
于 2013-08-05T06:19:09.367 回答