2

给定以下模型:

团队.rb

class Team < ActiveRecord::Base
    has_many :events, :dependent => :destroy
    has_many :challenges, :through => :events

    validates :name, :presence => true, :uniqueness => true
end

挑战.rb

class Challenge < ActiveRecord::Base
    has_many :events, :dependent => :destroy
    has_many :teams, :through => :events

    validates :name, :presence => true, :uniqueness => true
    validates :flag, :presence => true, :uniqueness => true
end

事件.rb

class Event < ActiveRecord::Base
    belongs_to :team
    belongs_to :challenge

    validates :team,      :presence => true
    validates :challenge, :presence => true
end

我想显示“排名”最高的团队。排名最高的团队完成的挑战最多(事件)。如果 X 项赛事打成平手,则首先完成第 X 项赛事的队伍排名最高。

所以我可以很容易地根据事件的数量对团队进行排序,然后显示它们。

像这样:

def index
    @teams = Team.includes(:events).
                  select("*, COUNT(events.id)").
                  group("teams.id, events.id").
                  order("COUNT(events.id) DESC")
end

但是我不知道如何处理有平局的情况。有人知道用 SQL 做这件事的好方法吗?

我宁愿使用 SQL 来执行此操作,而不是在应用服务器上执行额外的步骤。

谢谢!!

4

2 回答 2

1

You could try this:

 @teams = Team.includes(:events).
              select("*, COUNT(events.id) AS event_count, MAX(events.created_at) AS last_event_created_at").
              group("teams.id, events.id").
              order("event_count DESC, last_event_created_at ASC")
于 2012-06-07T23:59:22.763 回答
0

所以我让它工作了。谢谢xnm。你把我送到了正确的方向。不敢相信我忘记了MAX。:(

我还必须修复我的 GROUP BY ...

这是工作版本:

class Team < ActiveRecord::Base
    ...

    def self.ranked
        all(:select => "teams.*, COUNT(events.id) AS challenges_completed, MAX(events.created_at) AS last_event",
            :joins => "LEFT OUTER JOIN events ON events.team_id = teams.id",
            :group => "teams.id, events.team_id",
            :order => "challenges_completed DESC, last_event ASC")
    end
end
于 2012-06-12T01:24:40.150 回答