0

可能重复:
Rails ActiveRecord group_by & sum db results for use with Lazy HighCharts

我对 RoR/Ruby 完全陌生,我正在使用 Lazy High Charts gem 根据一些数据库信息生成一些 purdy 图表。

我已经尝试了提供的答案,但我仍然对如何做到这一点感到有些困惑..

我需要按月/年汇总 amount_used 和 billed_amount 和分组(例如,2012 年 8 月)

最终结果将类似于具有两个系列“使用量”和“成本”的双轴图表。此信息特定于某个 account_id。

在此处输入图像描述

发票表

+---------------+--------------+------+-----+---------+----------------+
| Field         | Type         | Null | Key | Default | Extra          |
+---------------+--------------+------+-----+---------+----------------+
| id            | int(11)      | NO   | PRI | NULL    | auto_increment |
| account_id    | int(11)      | YES  |     | NULL    |                |
| invoice_date  | varchar(255) | YES  |     | NULL    |                |
| amount_used   | float        | YES  |     | NULL    |                |
| billed_amount | float        | YES  |     | NULL    |                |
| comments      | text         | YES  |     | NULL    |                |
| created_at    | datetime     | NO   |     | NULL    |                |
| updated_at    | datetime     | NO   |     | NULL    |                |
+---------------+--------------+------+-----+---------+----------------+

控制器图表代码

@account = Account.find(params[:id])
@invoices = Invoice.where("account_id = #{@account.id}").order("invoice_date DESC")

@h = LazyHighCharts::HighChart.new('area') do |f|
  f.options[:chart][:defaultSeriesType] = "area"
  #Sample dates right now, should be the grouped_by :invoice_date
  f.xAxis( :categories => ['May', 'Jun', 'Jul'] )
  f.yAxis([
    {
      :title => { :text => "Amount Used" }
    },
    {
      :title => { :text => "Cost" },
      :opposite => true
    }
  ])
  #Sample data right now, should be the summed amounts of the :amount_used correpsonding for each above grouped invoice_date
  f.series(:name => "Amount Used", :data => [100,300,500] )
  #Sample data right now, should be the summed amounts of the :billed_amount correpsonding for each above grouped invoice date
  f.series(:name => "Cost", :yAxis => 1, :data => [200,400,600] )
end 
4

2 回答 2

3

关键是用来Enumerable#group_by查找所有同一月份的行,然后将它们相加:

require 'date'

# Simulate rows from your DB
Row = Struct.new(:date,:amount)
rows = DATA.read.scan(/(\S+) - (\d+)/).map do |date,amount|
    Row.new( Date.strptime(date,'%m/%d/%y'), amount.to_i )
end

sum_by_month = rows.sort_by(&:date).group_by do |row|
    row.date.strftime('%b/%Y')
end.map do |year_and_month,sub_rows|
    [ year_and_month, sub_rows.map(&:amount).inject(:+) ]
end

p sum_by_month
#=> [
#=>   ["Aug/2012", 22000],
#=>   ["Sep/2012", 5000],
#=>   ["Oct/2012", 76000]
#=> ]

__END__
08/01/12 - 10000
08/16/12 - 12000
09/13/12 - 5000
10/12/12 - 76000

对于您的特定用例,您可以这样使用:

<table><thead><tr><td></td>
  <%sum_by_month.each do |month,total|%>
    <th scope="col"><%=month%></th>
  <%end%>
</thead><tbody>
  <tr><th>Usage:</th>
  <%sum_by_month.each do |month,total|%>
    <td><%=total%></td>
  <%end%></tr>
</tbody></table>

或者,这是一种更直接的方法(我不推荐):

sum_by_month = {}
last_month = nil
total      = nil
@invoices.each do |inv|
  month = inv.date.strftime('%b/%Y')
  unless last_month==month
    sum_by_month[month] = total if last_month
    last_month = month
    total      = 0
  end
  total += inv.amount
end

# Make sure to add in the very last month
sum_by_month[month] = total if last_month
于 2012-09-07T19:42:43.480 回答
2

感谢您提供更多信息。您应该能够将所有这些分组并制作表格/等,而无需多次循环记录。

<% @invoices.group_by { |invoice| DateTime.strptime(invoice.invoice_date.to_s, '%m/%d/%y').strftime('%b/%Y') } do |day, invoices| %>
(@day_headings ||= []) << day  # make an array of your day/year table headings
(@day_counts ||= []) << invoices.sum(&:amount_used) # sum all the invoices amount_used, grouped under this heading
<% end %>

...现在你有了两个变量,你可以创建你的表

<table>
 <thead>
  <tr>
   <% @day_headings.each do |th| %>
    <th><%= th %></th>
   <% end %>
  </tr>
 </thead>
 <tbody>
  <tr>
   <th scope="row">Usage</th>
   <% @day_counts.each do |td| %>
    <td><%= td %></td>
   <% end %>
  </tr>
 </tbody>
</table>

以下是这些方法的文档:http: //api.rubyonrails.org/classes/Enumerable.html

于 2012-09-07T20:00:57.383 回答