Mysql
 sql >> Database >  >> RDS >> Mysql

Trova il massimo della somma in MySQL

Prova questo:

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

Ecco solo la query SQL per una più facile comprensione:

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