在MySQL中找到SUM的最大值 [英] Find The MAX of SUM in MySQL

查看:717
本文介绍了在MySQL中找到SUM的最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

good day guys currently I'm making PHP(inventory management) for my items, in my system customers can buy items , I save customer ID and number of sold Items in one table (called it Sell table) in MySQL , now I want to show the best customer.(who bought the most items in my system) I wrote a code to find out how many items each customer bought ,but I don't know how I can show the best customer see this code :

$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 />";
}

它向我的所有客户显示了已售出商品的数量,我需要显示具有最大卖出数量的特定客户. 例如,这是我的结果:

It shows all of my customers with numbers of sold items to them, I need to show the specific customer who has the maximum number of sell item . for example, this is my result :

售出数量:11至2:客户编号 售出数量:103至3:客户ID

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

但是我想要的只是显示:

but the thing I want is just show :

已售出数量:103至3:客户编号

Number of sold :103 to 3 :id of customer

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

I hope you guys can get me, thanks.

推荐答案

尝试一下:

$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查询:

Here is the SQL query alone for easier understanding:

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中找到SUM的最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆