Rails group_by总金额

时间:2012-08-17 09:38:20

标签: mysql ruby-on-rails group-by

我正在使用Rails& MySql,目前,我的数据在视图中显示如下:

Customer A, 5
Customer B, 3
Customer C, 2
Customer A, 2
Customer B, 4

我希望它显示如下:

Customer A, 7
Customer B, 7
Customer C, 2

目前我的.html.erb视图如下所示:

<% @licenses.each do |l| %>
<tr>
    <td><%= l.customer.companyname %></td>
    <td><%= l.customer.licensecontact %></td>
    <td><%= l.amount %></td>
    </td>
</tr>
<% end %>

我很确定我需要在@licenses.each之后添加一些内容我还不确定是什么?

1 个答案:

答案 0 :(得分:2)

根据您提供的非常少的信息,我认为您必须使用Group BY

SELECT customer, SUM(quantity) AS quantity FROM orders GROUP BY customer

使用Rails 3

Order.select("customer, SUM(quantity) AS quantity").group("customer")

使用Rails 2 #This也适用于Rails 3

Order.find(:all, :select => "customer, SUM(quantity) AS quantity", :group => "customer")

EDITED

你必须以类似的方式取消记录

@licenses = License.find_by_sql("SELECT c.companyname, c.licensecontact, SUM(l.amount) 
                                  FROM licenses l 
                                  LEFT JOIN customers c ON c.id=l.customer_id
                                  GROUP BY c.companyname, c.licensecontact")

将您的观点更改为以下

<% @licenses.each do |l| %>
<tr>
    <td><%= l.companyname %></td>
    <td><%= l.licensecontact %></td>
    <td><%= l.amount %></td>
    </td>
</tr>
<% end %>