SQL 使用 group_by 统计用户数

SQL using group_by to count users

users = [
        {"id":1, "zipcode":"10031"},
        {"id":4, "zipcode":"10000"},
        {"id":2, "zipcode":"10031"},
        {"id":3, "zipcode":"10031"}
      ]

大家好。我需要可以减少我的代码过程的帮助。 我有一个用户存储的数据。 我想在我的第一行代码中实现这个吗

  [
    {"id":1, "zipcode":"10000", "users_count": 1}, 
    {"id":2, "zipcode":"10031", "users_count": 3},
  ]

我的代码:

user = User.select(:zipcode).group(:zipcode).count(:id)

result of the above code is {"10000"=>1, "10031"=>3}

  keys = user.keys
  values = user.values
i = 0
num = keys.length.to_i
zipcodes = []
while i < num do
  zipcode = keys[i]
  users_count = values[i]
  zipcodes[i]= zipcode , users_count
  i +=1
end

result if the above code is [[10000, 1], [10031, 3]]

如果这段代码我想改变结果 user = User.select(:zipcode).group(:zipcode).count(:id)

from this {"10000"=>1, "10031"=>3}

to this [{"id":1, "zipcode":"10000", "users_count": 1},{"id":2, "zipcode":"10031", "users_count": 3}]

感谢您的帮助。

您可以这样修改您的查询,

user_counts = User.select(:zipcode, 'count(*) as user_count').group(:zipcode)

请注意,在控制台打印的结果中,不会显示 user_count,因为它不是用户模型的属性。但是它在那里,可以通过

访问
user_counts.each do |user_count|
  puts user_count.zip_code
  puts user_count['user_count']
end

您还可以通过将它们转换为JSON

来查看所有结果
user_counts = User.select(:zipcode, 'count(*) as user_count').group(:zipcode)
puts user_counts.as_json