每个属性组合得票最多的元素

Element with the most votes for each combination of attributes

在我的架构中,用户可以投票给具有不同力量(例如照明、火)和不同身体的不同怪物。 Body 是一个多态关联,因为它可以来自不同类型的动物。 这是架构的相关部分:

votes:
monster_id
power_id
body_id #polymorphic association
body_type #polymorphic association

对于权力和 body 的每个组合,在选票上有代表性 table,我想找出获得最多选票的怪物。

具体例子的例子:

--------------------------------------------------
| votes                                          |
--------------------------------------------------
| monster_id| power_id | body_id | body_type     |
--------------------------------------------------
| 1         | 1        | 1       | Body::Mammal  |
| 2         | 1        | 1       | Body::Mammal  |
| 2         | 1        | 1       | Body::Mammal  |
| 11        | 2        | 11      | Body::Reptile |
| 11        | 2        | 11      | Body::Reptile |
| 22        | 2        | 11      | Body::Reptile |
--------------------------------------------------

我想要的结果:

- ["For the combination (power_id: 1, body_id: 1, body_type: Body::Mammal), the monster with most votes is monster_id: 2",
"For the combination (power_id: 2, body_id: 11, body_type: Body::Reptile), the monster with most votes is monster_id: 11",
...]

我正在使用 Rails 6 和 postgres,所以我可以选择使用 ActiveRecord,对此我有一点偏好,但我意识到这可能需要原始 sql.

我知道答案很可能是这个问题中给出的答案的扩展,他们用更少的属性做类似的事情,但我似乎无法增加容纳增加的列数所需的额外复杂性在玩。 sql: select most voted items from each user

如果我没听错,你可以使用distinct on和聚合:

select distinct on (body_id, power_id, body_type) 
    body_id, power_id, body_type, monster_id, count(*) cnt_votes
from votes
group by body_id, power_id, body_type, monster_id
order by body_id, power_id, body_type, count(*) desc