我有一个像这样生成的表
ShopItem.select("shop_items.label_id, shop_items.store_id")
使用cols label_id: 7789, store_id: 4140
。现在我想找出每个标签有多少商店属于它。结果应该是{"label_id" => "number of stores for the label", ... }
任何人都可以给我一个如何做的提示吗?
(我使用的dbms是PostgreSQL,我通过Rails 3.2 ActiveRecord访问它)
答案 0 :(得分:0)
您需要使用COUNT
和GROUP BY
。
ShopItem.group(:store_id).count
它将返回一个Hash,其中键是:store_id
,值是数字。
{6323=>2, 31300=>1, 9631=>1}