【问题标题】:How to find the product_id with the most occurences and biggest quantity SQL如何找到出现次数最多、数量最多的product_id SQL
【发布时间】:2018-04-27 07:07:20
【问题描述】:

我正在申请管理库存,我的一项职能是报告。

我正在尝试制作一份基本的前五名产品销售报告,但我无法理解它的外观。

到目前为止,我可以返回表的 count() 的 max(),例如

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

现在,如果我在选择中添加 product_id,我会收到未知字段的错误:

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

我的两个问题是为什么我得到未知字段,因为我引用了表(尝试使用表名或派生的别名)以及如何获得前 5 个而不是第一个?非常感谢您的时间和耐心!

下面是erd和数据结构的图片

【问题讨论】:

  • 仔细查看您从第一个查询中获得的结果。意识到您目前没有计算 每个产品 COUNT(我猜您想要一个 SUM 代替)。如果您删除MAX,您仍然只会看到一个结果行。
  • 你确实是对的!所以,如果我更接近,我得到的是所有数量字段的计数?

标签: mysql sql mysql-error-1054


【解决方案1】:

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

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 
)

正如 Damien 所提到的,您可能需要 quantity 的总和超过每个 product_id 的记录数 sales_products。因此,在这种情况下,解决方案应该是

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 在 ALL/IN/ANY 子查询中不支持 LIMIT。解决方法如下:

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

【讨论】:

  • 工作就像一个魅力!我有几个问题 1:与我可以获得的结果数量有关,我怎样才能获得前 5 名? 2:从我刚刚读到的内容来看,HAVING 用于聚合函数 Liek sum() 因为 WHERE 无法处理它,对吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-22
  • 1970-01-01
  • 2020-07-05
  • 1970-01-01
  • 2011-06-05
相关资源
最近更新 更多