如何找到发生次数最多、数量最多的产品id

i2byvkas  于 2021-06-23  发布在  Mysql
关注(0)|答案(1)|浏览(419)

我正在申请管理库存,我的一个职能是报告。
我正试着做一份基本的前五名产品销售报告,但我根本不知道它应该是什么样子。
到目前为止,我可以返回表count()的max()

SELECT MAX(product_quantity) FROM 
(SELECT COUNT(quantity) as product_quantity FROM
sales_products) as derived;

现在,如果我在select中添加产品标识,我会得到一个error of unknown字段:

SELECT product_id, MAX(product_quantity) FROM 
    (SELECT COUNT(quantity) as product_quantity FROM
    sales_products) as derived;

我的两个问题是,既然我正在引用表(尝试使用表名或派生的别名),为什么要获取未知字段,以及如何获取前5个字段而不是第一个字段?非常感谢您的时间和耐心!
下面是erd和数据结构的图片

w8rqjzmb

w8rqjzmb1#

如果您想要销售数量最多的产品,请尝试以下查询

SELECT product_id, COUNT(quantity) as product_quantity 
FROM sales_products
GROUP BY product_id
HAVING COUNT(quantity) >= ALL(
    SELECT COUNT(quantity)
    FROM sales_products
    GROUP BY product_id 
)

正如达米恩所说,你可能需要 quantity 超过记录数 sales_productsproduct_id . 因此,在这种情况下,解决办法应该是

SELECT product_id, SUM(quantity) as product_quantity 
FROM sales_products
GROUP BY product_id
HAVING SUM(quantity) >= ALL(
    SELECT SUM(quantity)
    FROM sales_products
    GROUP BY product_id 
)

编辑:(op问题:与我能得到的结果数量有关,我怎样才能得到前5名?)
这可能有点棘手,因为mysql不支持 LIMITALL/IN/ANY 子查询。解决方法如下:

SELECT product_id, SUM(quantity) as product_quantity 
FROM sales_products
GROUP BY product_id
HAVING SUM(quantity) >= (
    SELECT MIN(quantity_sum)
    FROM
    (
        SELECT SUM(quantity) quantity_sum
        FROM sales_products
        GROUP BY product_id 
        ORDER BY SUM(quantity) desc
        LIMIT 5
    ) t
)

编辑2:如果你只关心前5名,而不关心领带(这意味着你可以拥有前10名的产品,数量相同,你可以随机选择5个),那么你可以使用这个

SELECT product_id, SUM(quantity) as product_quantity 
FROM sales_products
GROUP BY product_id
ORDER BY SUM(quantity) desc
LIMIT 5

相关问题