Home>
Thing I want to do

Count duplicates for a particular column (country) in rails
Extract only country and sort by group in descending order of duplication

Users table

id country name group
1 Japan Toda A
2 Korea Lee Dae Ho A
3 America Trump A
Four Japan Erika A
Five Japan Ashida A
6 America Gatlin A
7 Iceland Sherry B
8 Puerto Rico Johnson B
9 Iceland Sally B
Expected output
["Japan", "America", "Korea"] #Group A
["Iceland", "Puerto Rico"] #Group B
Practice

I searched various things such as sort, uniq, distinct, but I can't handle it easily.
I'm writing code for a long time now
I'm trying to put country in an array and count the countries in the array but it doesn't work
If there is another good way, please teach me

group = ["A", "B"]
a = 0
country = []
2.times do
  a = User.where (group: group [a]). pluck (: country)
  country<
Postscript

I'm also trying to handle how many duplicates there were

  • Answer # 1

    Let's enjoy SQL ...

    Users.pluck (: group ,: contry).
          group_by {| g, c | g}.
          map {| g, countries |
              c_size =
                 countries.group_by {| c | c}.
                          map {| c, ary | [c, ary.size]}.
                          sort_by {| c, size | -size}.
                          map {| ary | ary.first.first}
              [g, c_size]
           } .to_h