根据不同的列对记录组进行排序

时间:2013-05-06 20:44:58

标签: ruby-on-rails ruby-on-rails-3 postgresql ruby-on-rails-3.1 ruby-on-rails-3.2

我在表格中有四列称为记录,例如得分,event_id,user_id,我想根据用户ID +事件ID对记录的得分求和, 然后我想向用户展示按分数排序的不同事件。

所以我已经完成了下面的代码

Recording.select("user_id,event_id,sum(score) as score").group(:user_id,:event_id).order("score DESC")

以上查询根据最高得分输出记录,如下所示得分

 #<Recording user_id: 4, event_id: 51, score: 64622>,
 #<Recording user_id: 3, event_id: 51, score: 5912>
 #<Recording user_id: 4, event_id: 31, score: 62>, 
 #<Recording user_id: 3, event_id: 48, score: 0>

但是我希望重新调整下面的结果(按分数排序的不同事件的用户)

 #<Recording user_id: 4, event_id: 51, score: 64622>,
 #<Recording user_id: 4, event_id: 31, score: 62>, 
 #<Recording user_id: 3, event_id: 48, score: 0>,
 #<Recording user_id: 3, event_id: 51, score: 5912>

1 个答案:

答案 0 :(得分:1)

对于PostgreSQL,您可以使用窗口函数来执行此操作:

select_sql <<-SELECT
  user_id, event_id, sum(score) as score, 
  ROW_NUMBER() OVER (PARTITION BY user_id, event_id ORDER BY sum(score) DESC) as rowNum
SELECT

subquery = Recording.select(select_sql).group(:user_id, :event_id).to_sql

Recording.select("*").from(Arel.sql("(#{subquery}) t")).
          order("rowNum, score DESC")