I have been fighting with this to long and need some help. I can't seem to figure out why my subtotals and not correct. The grand total at the end is correct
Here is the code that I'm using:
$sql = "SELECT COUNT(polk_data.state),
COUNT(polk_data.make),
polk_data.make,
polk_data.state,
polk_data.body,
states.state,
states.abv_state
FROM polk_data, states
WHERE polk_data.body = 'livestock'
AND polk_data.state = states.abv_state
GROUP BY(states.abv_state),(polk_data.make)
ORDER BY states.abv_state DESC, polk_data.make ASC";
$result = mysql_query($sql,$cn) or die($sql.mysql_error())
$sub_total_state = '';
$total = 0;
while ($row = mysql_fetch_assoc($result)) {
if($total == 0) {
$sub_total_state = $row['state'];
}
$total += $row['COUNT(polk_data.make)'];
if($row['state'] != $sub_total_state) {
if($sub_total_state != '')
print "Total For ".$sub_total_state." = ".$sub_total;
print "<br><br>";
$sub_total_state = $row['state'];
$sub_total = $row['COUNT(polk_data.make)'];
}
else {
$sub_total = $row['COUNT(polk_data.make)'];
}
print $row['state'];
print " ".(ucwords(strtolower($row['make'])));
print " sold " . $sub_total;
print "<br>";
}
if($sub_total_state != '')
print "Total For ".$sub_total_state." = ".$sub_total;
print "<br><br>";
print "Grand Total = " . $total . " Trailers sold";
mysql_close($cn);
Now what I'm getting is:
Wyoming Barrett Trailer sold 1
Wyoming Merritt Eqpt sold 1
Wyoming Wilson Trailer sold 6
Total For Wyoming = 6
// Should be a total of 8
West Virginia M H Eby sold 1
West Virginia Merritt Eqpt sold 2
Total For West Virginia = 2
// Should be a total of 3
Wisconsin M H Eby sold 2
Wisconsin Wilson Trailer sold 3
Total For Wisconsin = 3
// Should be a total of 5
Washington Wilson Trailer sold 3
Total For Washington = 3
Virginia Barrett Trailer sold 1
Virginia Merritt Eqpt sold 1
Total For Virginia = 1
// Should be a total of 2
Utah Merritt Eqpt sold 15
Utah Wilson Trailer sold 10
Total For Utah = 10
// Should be a total of 25
Grand Total = 46 Trailers sold
Now the grand total is correct but as you can see the sub totals for each state is not correct, it looks like its just picking up the last one instead of adding them, I cant figure it out so any help would be greatly appreciated