About Me

Friday, 13 April 2012

MySQL Aggregate Functions - SUM()

MySQL Aggregate Functions - SUM()


Products Table:

idnametypeprice
123451Park's Great HitsMusic19.99
123452Silly PuddyToy3.99
123453PlaystationToy89.95
123454Men's T-ShirtClothing32.50
123455BlouseClothing34.97
123456Electronica 2002Music3.99
123457Country TunesMusic21.55
123458WatermelonFood8.73

MySQL SUM - Totaling Groups

SUM is an aggregate function that totals a specific column for a group. The "products" table that is displayed above has several products of various types. One use of SUM might be to find the total of all the items' price for each product type.
Just as we did in the aggregate introduction lesson, we are going to apply the aggregate function to price and GROUP BY type to create four groups: Music, Toy, Clothing and Food.

PHP and MySQL Code:

<?php
// Make a MySQL Connection

$query = "SELECT type, SUM(price) FROM products GROUP BY type"; 
  
$result = mysql_query($query) or die(mysql_error());

// Print out result
while($row = mysql_fetch_array($result)){
 echo "Total ". $row['type']. " = $". $row['SUM(price)'];
 echo "<br />";
}
?>

Display:

Total Clothing = $67.47
Total Food = $8.73
Total Music = $45.53
Total Toy = $93.94

0 comments:

Post a Comment