2

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 :

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 :

Number of sold :103 to 3 :id of customer

I hope you guys can get me, thanks.

3 Answers 3

4

Try this:

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

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
Sign up to request clarification or add additional context in comments.

1 Comment

In case there are several best customers with equal amount of bought items, this code will show all of them. The one by hjpotter92 won't.
1

There are two methods for that(which I can think of). Both need change in your SQL query.

Sol. 1

$test= "SELECT c_id, MAX( SUM(n_sell) ) FROM sell GROUP BY c_id ";

Sol. 2

$test= "SELECT c_id, SUM(n_sell) FROM sell GROUP BY c_id ORDER BY SUM(n_sell) DESC LIMIT 1";

The remaining section of your code may remain the same.

2 Comments

Thanks , I wrote the first method before,It dosen't work in my system ,don't know why , but second one is new for me , thanks alot. It works....
The MAX(SUM( )) will not work as you expect. Please edit your answer.
1

Use ORDER BY .

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.