【问题标题】:Count group by operation for intermediate table中间表的按操作计数分组
【发布时间】:2014-11-06 14:59:36
【问题描述】:

我有一个这样生成的表

ShopItem.select("shop_items.label_id, shop_items.store_id")

与列label_id: 7789, store_id: 4140。现在我想知道,对于每个标签,有多少家商店属于它。结果应该类似于{"label_id" => "number of stores for the label", ... }

谁能告诉我怎么做?

(我使用的dbms是PostgreSQL,我通过Rails 3.2 ActiveRecord访问它)

【问题讨论】:

    标签: ruby-on-rails postgresql ruby-on-rails-3.2


    【解决方案1】:

    您需要使用COUNTGROUP BY

    ShopItem.group(:store_id).count
    

    它会返回一个哈希,键是:store_id,值是数字。

    {6323=>2, 31300=>1, 9631=>1}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-03-09
      • 2021-01-05
      • 2015-10-15
      • 2013-05-17
      • 1970-01-01
      • 2022-09-22
      • 2011-08-29
      相关资源
      最近更新 更多