0

我在表中有四列称为记录,例如分数、事件 ID、用户 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>
4

1 回答 1

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")
于 2013-05-06T20:56:17.813 回答