从每个品牌中选择前2名畅销产品

时间:2018-03-17 09:55:40

标签: mysql select group-by mysql-5.7

像这样的简单查询:

SELECT
    products.*,
    SUM(orderdetails.quantity) AS sold
FROM products
RIGHT JOIN orderdetails ON orderdetails.product_id = products.id
GROUP BY products.id, products.brand_id
ORDER BY sold DESC

如何更改它以获得每个品牌的两种产品?

1 个答案:

答案 0 :(得分:1)

以下代码对您有所帮助,

 SELECT ranked.*
   FROM
     (SELECT products.*, 
             @product_rank := IF(@current_brand = products.brand_id, @product_rank + 1, 1) AS product_rank,
             @current_brand := products.brand_id 
       FROM ( SELECT
              products.*,
              SUM(orderdetails.quantity) AS sold
              FROM products
              JOIN orderdetails ON orderdetails.product_id = products.id
              GROUP BY products.id, products.brand_id
              ORDER BY products.brand_id,sold  DESC
             ) products      
     ) ranked
   WHERE product_rank <= 2

SqlFiddle Demo Here