Is there a SQL query for rails 3/active records that does most/all the work to fill an array or hash with all the values (and counts) that a field contains?
是否存在对rails 3 /活动记录的SQL查询,它使用字段包含的所有值(和计数)来填充数组或散列的大部分/全部工作?
For example, a list (and count) of all the city names that customers are in:
例如,客户所在的所有城市名称的列表(和计数):
If customer.city contains dallas, paris, chicago, dallas, houston, dallas, paris
如果customer.city包含dallas,paris,chicago,dallas,houston,dallas,paris
I need to generate the list
我需要生成列表
chicago 1
dallas 3
houston 1
paris 2
Of course it's easy to do it by iterating, but I'm thinking there's a way to most/all the work in a good SQL query?
当然通过迭代很容易实现,但我认为有一种方法可以在一个好的SQL查询中完成大部分/全部工作?
3 个解决方案
#1
2
I'm confused... do you mean like this?
我很困惑......你的意思是这样吗?
Customer.group('city').count
#2
1
SELECT city_name, count(city_name) FROM customers GROUP BY city_name
#3
0
def dup_hash
inject(Hash.new(0)) { |h,e| h[e] += 1; h }.select {
|k,v| v > 0 }.inject({}) { |r, e| r[e.first] = e.last; r }
end
puts customer.city.dup_hash
def dup_hash inject(Hash.new(0)){| h,e | h [e] + = 1; h} .select {| k,v | v> 0} .inject({}){| r,e | r [e.first] = e.last; r} end puts customer.city.dup_hash
You can try this in irb.
你可以在irb中尝试这个。
#1
2
I'm confused... do you mean like this?
我很困惑......你的意思是这样吗?
Customer.group('city').count
#2
1
SELECT city_name, count(city_name) FROM customers GROUP BY city_name
#3
0
def dup_hash
inject(Hash.new(0)) { |h,e| h[e] += 1; h }.select {
|k,v| v > 0 }.inject({}) { |r, e| r[e.first] = e.last; r }
end
puts customer.city.dup_hash
def dup_hash inject(Hash.new(0)){| h,e | h [e] + = 1; h} .select {| k,v | v> 0} .inject({}){| r,e | r [e.first] = e.last; r} end puts customer.city.dup_hash
You can try this in irb.
你可以在irb中尝试这个。