LoginSignup
38
37

More than 5 years have passed since last update.

Railsでグループ単位で集計(SUM)する例

Last updated at Posted at 2014-07-16

自分向けのメモ

ユーザー毎のスコアを集計するような例

TestModel.group(:user_id).sum(:score)

以下のSQLが生成される。

SELECT SUM(`test_models`.`score`) as sum_score, user_id, FROM `test_models` GROUP BY user_id

上位10位までに制限する例

TestModel.limit(10).order('sum_score desc').group(:user_id).sum(:score)
38
37
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
38
37