【问题标题】:Selecting Max Value and Key mySQL选择最大值和键 mySQL
【发布时间】:2017-03-28 12:59:45
【问题描述】:

我知道这可能是一个非常简单的解决方法,但我无法全神贯注。

我有一张 factproductsales 表,其中包含所有交易的销售额。我必须找出哪个产品的销量最高。我必须提供 productID 和金额。

这是我所拥有的:

SELECT productid, MAX(salestotalcost) 
FROM factproductsales

它给了我正确的数量,但它给了我错误的 productid。它应该是 5,但给了我 1。我认为我犯的错误是一个非常明显的错误。感谢您的帮助

【问题讨论】:

标签: php mysql


【解决方案1】:
SELECT productid, MAX(salestotalcost) as max_cost FROM factproductsales group by productid order by max_cost desc limit 5;

使用Group By,排序并限制5,以找到最大saletotalcost

【讨论】:

    【解决方案2】:

    试试这个:

    SELECT productid, MAX(salestotalcost) as max
    FROM factproductsales GROUP BY productid
    ORDER BY max DESC LIMIT 5
    

    【讨论】:

    • 这为我提供了每个 productID 的所有最大 salestotalcost,而我只需要最高值。感谢您的帮助
    • 我添加了 ORDER 和 LIMIT
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-24
    • 2021-09-28
    • 2016-02-16
    相关资源
    最近更新 更多