【问题标题】:Ruby on rails count and groupRuby on rails 计数和分组
【发布时间】:2011-10-16 22:12:06
【问题描述】:

需要构建一个与 SQLite 和 Postgres 一起使用的“Top 10”查询。

客户端模型 客户has_many :merchandises, :through => :orders, :source => :items

我想按 product_id 对订购的商品进行分组,获取每个商品的计数,然后按订购最多的商品排序,限制为 10 个。

Client.last.merchandises.group(:product_id).count(:quantity)
SELECT COUNT("items"."quantity") AS count_quantity, product_id AS product_id FROM "items" INNER JOIN "orders" ON "items"."order_id" = "orders"."id" WHERE "orders"."client_id" = 2 GROUP BY product_id
=> {1=>91, 2=>1, 12=>1, 32=>1, 33=>1, 34=>1, 37=>1, 75=>1, 84=>1, 85=>1}

缺少什么:排序,限制为 10 并获取 product.name 以及数量计数

最新发展:

项目被选中但需要显示product.name

class Client < ActiveRecord::Base 
def top_ten_products
  Item.find_by_sql(
    "SELECT i.product_id, sum(i.quantity) AS sum_quantity
    FROM   orders o
    JOIN   items i ON i.order_id = o.id 
    WHERE  o.client_id = 2 
    GROUP  BY 1
    ORDER  BY 2 DESC
    LIMIT  10;"
   )
 end

控制台输出

=> [#<Item product_id: 1>, #<Item product_id: 37>, #<Item product_id: 75>, #<Item product_id: 12>, #<Item product_id: 32>, #<Item product_id: 33>, #<Item product_id: 2>, #<Item product_id: 34>, #<Item product_id: 84>, #<Item product_id: 85>] 

客户#show

<%= @client.top_ten_products %>

【问题讨论】:

    标签: sql ruby-on-rails-3 postgresql group-by


    【解决方案1】:

    假设product_id 是表items 的列,则查询在PostgreSQL 中可能如下所示:

    SELECT i.product_id
          ,p.name
          ,sum(i.quantity) AS sum_quantity
    FROM   orders o
    JOIN   items i ON i.order_id = o.id 
    LEFT   JOIN product p USING (product_id)
    WHERE  o.client_id = 2 
    GROUP  BY 1,2
    ORDER  BY 3 DESC, 2 -- with same quantity, order by name
    LIMIT  10;
    

    注意:

    我将您的数量聚合更改为 sum 并为 count 添加了一个评论列,因为我怀疑您错误地在想要总和的地方进行了计数。

    编辑2:

    sum() 已确认。 每个请求包含来自表产品的名称。
    LEFT JOIN 只是表 product 中缺少条目的预防措施,如果保证引用完整性,它可以是一个普通的 JOIN

    【讨论】:

    • 谢谢。差不多好了。我用最新的发展编辑了我上面的问题
    • 感谢您的更新,但项目下没有名称列。名称列是产品表的一部分。请指教。
    • @Gaelle:我在猜测中进行了编辑。如果不是这样,您需要提供表 product 如何链接到表 item 的信息。
    • 这是我不确定的地方。现在我有Item belongs_to :product,但产品表中没有任何内容,因为我不确定它应该如何设置。请指教。谢谢
    • @Gaelle:你在两个表中都看到了product_id 列吗? IOW,我的最新版本有用吗?试试SELECT * FROM product LIMIT 10SELECT * FROM item LIMIT 10 看看并弄清楚它们是如何联系在一起的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-06
    • 1970-01-01
    • 2014-08-14
    • 2014-10-08
    • 2016-06-17
    • 2011-01-28
    相关资源
    最近更新 更多