【发布时间】: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