这个标题不是很具描述性;我不知道如何缩短我的问题...
假设我有weightlifters
的表格,其中name
,pounds
和type_of_lift
为字段。该表中有数百个条目。我想找回表中总磅数最高的10人。我写了以下内容:
Weightlifter.order("pounds DESC").limit(10)
这项工作很好,除了我想要累积权重。因此,如果一个人不止一次进入前10名,我不希望他的名字被列出两次,我想将权重加在一起并将它们显示为总和。如果我有:
"Johnny", "300", "Bench"
"Wesley", "295", "Bench"
"Johnny", "280", "Clean"
...
"Timmy", "150", "Curl"
我希望用580磅显示约翰尼,用300磅显示约翰尼,再用280磅显示约翰尼。
这是怎么做到的?
Ruby 1.9.3,Rails 3.2.6,SQLite3 3.6.20
谢谢!
答案 0 :(得分:2)
它应该是这样的
Weightlifter.select('name, type_of_lift, sum(pounds) as pounds').
group('name').
order("sum(pounds) DESC").
limit(10)
这是一个很好的指南:ActiveRecord Query Interface。
答案 1 :(得分:1)
# in your WeightLifter model
class Weightlifter < ActiveRecord
attr_accessor :weight_total
# WeightLifterController
lifters = []
Weightlifter.order("pounds DESC").each do |lifter|
return lifters if lifters.count == 10
if !lifters.collect{|a| a[:name] }.include?(lifter.name)
lifters << lifter
local_lifter = lifters.where(name: lifter.name).first
local_lifter.weight_total = lifter.weight
else
local_lifter = lifters.where(name: lifter.name).first
local_lifter.weight_total = local_lifter.weight_total + lifter.weight
end
end