mysql - 如何找到出现次数最多、数量最大的product_id SQL

标签 mysql sql mysql-error-1054

我正在申请管理库存的应用程序,我的职能之一是报告。

我正在尝试制作一份基本的前五名产品销售报告,但我根本无法理解它应该是什么样子。

到目前为止,我可以返回表的 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的图片和数据结构

DB_ERD

DB_structure

最佳答案

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

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 所提到的,您可能需要的数量总和大于每个product_idsales_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

关于mysql - 如何找到出现次数最多、数量最大的product_id SQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50057124/

相关文章:

mysql - #1054 - 未知列 - SQL 查询问题

php - 用于创建 URL 的简单 PHP 应用程序,例如 <ROOT_URL>/twitter_username

mysql - 计算重复字段上连接的结果

python - transaction.commit_unless_managed() python有什么用

mysql - PowerShell - 保存路径中的无效字符

带条件左外连接的 Mysql 子查询

Java将结果集转换为实体

sql - 外键引用多个表

没有 UDF 的 SQL 检查约束

mysql - 试图获得月份数