开发者

rails 3: best SQL query to list + count all existing values of a field?

开发者 https://www.devze.com 2023-03-05 09:15 出处:网络
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?

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?

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

I need to generate the list

chicago 1
dallas 3
houston 1
paris 2

O开发者_Go百科f 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?


I'm confused... do you mean like this?

Customer.group('city').count


SELECT city_name, count(city_name) FROM customers GROUP BY city_name


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消