LoginSignup
1
1

More than 5 years have passed since last update.

ActiveRecordでgroup by でcountした結果をcountされた結果でソートする

Last updated at Posted at 2016-09-22

以下のテーブル構造から、ASINでグルーピングして、countを取る。

id ASIN
1 1111111111
2 2222222222
3 3333333333
4 2222222222
 Model.group(:asin).count(:id)

上記の実行結果

{"1111111111" => 1,
"2222222222" => 2,
"3333333333" => 1,
}

これを、count結果の降順に並べる。

Model.group(:asin).order('count_id desc').count(:id)
{"2222222222" => 2,
"1111111111" => 1,
"3333333333" => 1,
}

これで求める結果が取れた。

ポイントは、最初の実行結果のログから、count_idという別名がつけられるので、
それをorderに指定する。
また、指定の際には文字列で渡してあげること。

Model.group(:asin).order(count_id: :desc).count(:id)

これだと、実行されるSQLは

SELECT 
  COUNT(Table.`id`) AS count_id, asin AS asin 
FROM Table 
WHERE Table.`deleted_at` IS NULL 
GROUP BY Table.`asin` 
ORDER BY Table.`count_id` DESC`

となり、Table.count_id がなくて怒られる。

結構使う場面は多そうなので、残しておく。

1
1
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
1
1