Ruby on rails计数和组

时间:2011-10-16 22:12:06

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

需要构建一个适用于SQLite和Postgres的“十大”查询。

客户端模型 客户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>] 

客户端#节目

<%= @client.top_ten_products %>

1 个答案:

答案 0 :(得分: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添加了一个注释列,因为我怀疑您错误地计算了您想要总和的数量。

EDIT2:

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