ruby 如何在活动记录中使用组获取列值之和

hzbexzde  于 2023-04-05  发布在  Ruby
关注(0)|答案(1)|浏览(84)

我有一个名为Competiton的表,其中包含以下列

id contestant_id m1 m2 m3 total judge_id feedback
1        1       3   3  3   6       1        xxx
2        1       4   4  2   10      2        yyy
3        1       2   4  2   8       3        yzz
4        2       4   4  2   10      2        ss
5        3       2   4  2   8       3        yzccz

我想得到一个参赛者的总成绩。例如out可以是这样的

contestant_id total 
      1         24 
      2         10
      3          8

我试过以下几种方法

Competiton.group('contestant_id ').select("contestant_id , sum(total ) ")

我得到的错误为column "competiton.id" must appear in the GROUP BY clause or be used in an aggregate function
有人可以帮助我的活动记录查询,以实现这一点?提前感谢. PS:我想在Active admin中使用scoped_collection中的查询

roqulrg3

roqulrg31#

你可以调用Competition.group(:contestant_id).sum(:total)
在您的示例中,您应该得到以下结果:

{3=>8, 2=>10, 1=>24}

键是contestant_id,值是total的和。

相关问题