选择字段的总和

时间:2012-07-27 23:29:58

标签: ruby-on-rails ruby sqlite activerecord

这个标题不是很具描述性;我不知道如何缩短我的问题...

假设我有weightlifters的表格,其中namepoundstype_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

谢谢!

2 个答案:

答案 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