mysql - 在 MySQL 中查找 SUM 的最大值

标签 mysql sum max

大家好 目前我正在为我的商品制作 PHP(库存管理),在我的系统中客户可以购买商品,我将客户 ID 和已售商品的数量保存在 MySQL 的一个表(称为销售表)中,现在我想展示最好的客户。(谁在我的系统中购买了最多的商品) 我写了一个代码来找出每个客户购买了多少商品,但我不知道如何向最好的客户展示 看这段代码:

$test= "SELECT c_id, SUM(n_sell) FROM sell GROUP BY c_id "; 
$resut = mysql_query($test) or die(mysql_error());
while($t = mysql_fetch_array($resut)){
    echo "Number of sold: ". $t['SUM(n_sell)'] ." to". $t['c_id'] .":id of customer";
    echo "<br />";
}

它向我的所有客户显示已售商品的数量,我需要显示拥有最大销售商品数量的特定客户。 例如,这是我的结果:

Number of sold: 11 to 2 :id of customer Number of sold: 103 to 3: id of customer

但我想要的只是展示:

Number of sold :103 to 3 :id of customer

我希望你们能得到我, 谢谢。

最佳答案

试试这个:

$test = "SELECT c_id, MAX(Bought) AS MaxBought FROM (SELECT c_id, SUM(n_sell) AS Bought FROM sell GROUP BY c_id) AS tmp HAVING MAX(Bought) = tmp.Bought"; 
$resut = mysql_query($test) or die(mysql_error());
while($t = mysql_fetch_array($resut)){
    echo "Number of sold: ". $t['MaxBought'] ." to". $t['c_id'] .":id of customer";
    echo "<br />";
}

为了便于理解,这里单独使用 SQL 查询:

SELECT c_id, MAX(Bought) AS MaxBought
FROM (SELECT c_id, SUM(n_sell) AS Bought
      FROM sell
      GROUP BY c_id) AS tmp
HAVING MAX(Bought) = tmp.Bought

关于mysql - 在 MySQL 中查找 SUM 的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9850879/

相关文章:

php, mysql 如果$a 在数据库中

php - 单个字段上的 SQL 多个条件

mysql - 类别和标签的数据结构

php - SQL 连接 QUERY 多个表和 SELECT

sql - SAS层次结构总和

Python Pandas Dataframe idxmax 太慢了。备择方案?

mysql - SELECT SUM 查询不断收到错误

c++ - OpenCL数据并行求和成一个变量

mysql 在给定其他值的约束条件下选择总和最大的记录

SQL查询: Using DISTINCT/UNIQUE and SUM() in one statement