Solved

MySQL query to output SUM for each of two columns, for multiple clients.

Posted on 2011-09-24
9
303 Views
Last Modified: 2012-05-12
I have a report page that lists information for each Client -- the client details from the 'client' table, and their billing details from the 'billing table'. This all works great.

I need to be able to SUM the 'charge' and 'payment' fields for each client and output that below each client's data table (output to html). Ideally these values would be set as variables so that I could then perform a difference calculation and display the balance. If there's a better way, please let me know.

I can't figure out how to modify my SQL query to include these values since they will change for each client.

Here's my Query:

SELECT * from client, billing WHERE client.id = billing.client ORDER BY client.id DESC

Open in new window


Here's my full code:
<?
$account = ''; // Declare Account to Empty

$sql = "SELECT * from client, billing WHERE client.id = billing.client ORDER BY client.id DESC";
$result = mysql_query($sql) or die(mysql_error());

// Keeps getting the next row until there are no more to get
while($row = mysql_fetch_array($result)){
   if ($row['account'] != $account) { // check if new account
        $account = $row['account'];
        if ($cnt > 0) echo '</tr></table><br />'; // check if open table row
        $cnt = 0; // set $cnt to zero and echo table row for new account
        echo "<table border='0' width='800px' align='center' cellpadding='1' color='white'><td colspan='6'><hr></td></tr><tr bgcolor='green'><th><b><font color='white' face='arial' size='2'>Client ID</b></font></th><th><font color='white' face='arial' size='2'><b>First Name</b></font></th><th><font color='white' face='arial' size='2'><b>Last Name</b></font></th><th><font color='white' face='arial' size='2'><b>Case Style</b></font></th><th><font color='white' face='arial' size='2'><b>Accident Date</b></font></th><th><font color='white' face='arial' size='2'><b>SOL Expires</b></font></th></tr>";
        echo "<tr><td align='center'>";
        echo $row['account'];
        echo "</td><td align='center'>";
        echo $row['fname'];
        echo "</td><td align='center'>";
        echo $row['lname'];
        echo "</td><td align='center'>";
        echo $row['casestyle'];
        echo "</td><td align='center'>";
        echo $row['accidentdate'];
        echo "</td><td align='center'>";
        echo $row['solexpires'];
        echo "</td></tr></table>";
        echo "<br /><table border='0' width='800px' align='center' cellpadding='1' bgcolor='white'>";
        echo "<tr><th>Date</th><th>Client ID</th><th>Transaction Type</th><th>Charge</th><th>Billed From</th><th>Payment</th></tr>";
        }
        if($color == "silver") {
     $color = "white";
    } else {
      $color = "silver";
    }

        if ($cnt == 0) echo '<tr>';
        // Print out the contents of each row into a table
        echo "<td align='center'>";
        echo $row['date'];
        echo "</td><td align='center'>";
        echo $row['account'];
        echo "</td><td align='center'>";
        echo $row['job_type'];
        echo "</td><td align='center'>";
        echo $row['charge'];
        echo "</td><td align='center'>";
        echo $row['job_type'];
        echo "</td><td align='center'>";
        echo $row['payment'];
        echo "</td></tr>";
        $cnt++;
}
echo "</table>";
?>

Open in new window


Here's what the output looks like, now --
Reports Table
Thanks in advance for your help.
0
Comment
Question by:goodie069
  • 4
  • 3
  • 2
9 Comments
 
LVL 3

Expert Comment

by:dkellner
ID: 36593245
It's a GROUP BY situation.

SELECT
    client.id,sum(charge),sum(payment)
    from client, billing WHERE client.id = billing.client
GROUP BY client.id
ORDER BY client.id DESC

Also, I'd recommend to read about LEFT JOIN.
0
 

Author Comment

by:goodie069
ID: 36593256
I'm assuming that would be a new query, as that wouldn't produce the necessary output for the existing tables. If so, where would I put that?

This isn't my script... I'm just trying to hack it to make it do what I need it to do.

Thanks for your help.
0
 
LVL 3

Expert Comment

by:dkellner
ID: 36593289
Try it in phpMyAdmin to test if the results are OK.

Then, if you want to simulate an output exactly like the first query does, use "sum(charge) as charge" or similar - that is, querying a sum and renaming it in the result set.  Maybe with this technique you can load the information to those fields that otherwise display the single "charge" values.

I mean, if you're hacking, this is one way to hack it.

A better advice is not to just patch the code but understand its logic and change it smartly.
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 83

Accepted Solution

by:
Dave Baldwin earned 500 total points
ID: 36593298
After line 28 above, create or clear a variable for each like $charges = 0;  $payments = 0;  In the bottom section, add each item like $charges += $row['charge'] and $payments += $row['payment'] .  Then at line 53, add one more row to your table that displays the results in the correct column.
0
 

Author Comment

by:goodie069
ID: 36593340
DaveBaldwin --

Fantastic! It's nearly perfect -- the only problem I'm having now is that I'm only getting the summed row for the last table on the page. I'm playing the trial and error game now trying to figure out where this should be, but if you see my mistake please let me know.

Either way, thank you for pointing me in the right direction!

<?
$account = ''; // Declare Account to Empty

$sql = "SELECT * from client, billing WHERE client.id = billing.client ORDER BY client.id DESC";
$result = mysql_query($sql) or die(mysql_error());

// Keeps getting the next row until there are no more to get
while($row = mysql_fetch_array($result)){
   if ($row['account'] != $account) { // check if new account
        $account = $row['account'];
        if ($cnt > 0) echo '</tr></table><br />'; // check if open table row
        $cnt = 0; // set $cnt to zero and echo table row for new account
        echo "<table border='0' width='800px' align='center' cellpadding='1' color='white'><td colspan='6'><hr></td></tr><tr bgcolor='green'><th><b><font color='white' face='arial' size='2'>Client ID</b></font></th><th><font color='white' face='arial' size='2'><b>First Name</b></font></th><th><font color='white' face='arial' size='2'><b>Last Name</b></font></th><th><font color='white' face='arial' size='2'><b>Case Style</b></font></th><th><font color='white' face='arial' size='2'><b>Accident Date</b></font></th><th><font color='white' face='arial' size='2'><b>SOL Expires</b></font></th></tr>";
        echo "<tr><td align='center'>";
        echo $row['account'];
        echo "</td><td align='center'>";
        echo $row['fname'];
        echo "</td><td align='center'>";
        echo $row['lname'];
        echo "</td><td align='center'>";
        echo $row['casestyle'];
        echo "</td><td align='center'>";
        echo $row['accidentdate'];
        echo "</td><td align='center'>";
        echo $row['solexpires'];
        echo "</td></tr></table>";
        echo "<br /><table border='0' width='800px' align='center' cellpadding='1' bgcolor='white'>";
        echo "<tr><th>Date</th><th>Client ID</th><th>Transaction Type</th><th>Charge</th><th>Billed From</th><th>Payment</th></tr>";
        $charges = 0;
        $payments = 0;
        }

        if ($cnt == 0) echo '<tr>';

        // SUM up the Charges & Payments
        $charges += $row['charge'];
        $payments += $row['payment'];
        $chargesP = number_format($charges,2);
        $paymentsP = number_format($payments,2);

        // Print out the contents of each row into a table
        echo "<td align='center'>";
        echo $row['date'];
        echo "</td><td align='center'>";
        echo $row['account'];
        echo "</td><td align='center'>";
        echo $row['job_type'];
        echo "</td><td align='center'>";
        echo $row['charge'];
        echo "</td><td align='center'>";
        echo $row['job_type'];
        echo "</td><td align='center'>";
        echo $row['payment'];
        echo "</td></tr>";
        $cnt++;
}
echo "<tr><td></td><td></td><td></td><td align='center'>";
echo '<b>' . $chargesP . '</b>';
echo "</td><td></td><td align='center'>";
echo '<b>' . $paymentsP . '</b>';
echo "</td></tr></table>";
?>

Open in new window


Reports Table
0
 

Author Comment

by:goodie069
ID: 36593460
Yeah, I can't figure out how to make the last row with the "sums" display as the last row of all tables... As shown in the screenshot in my previous response, it's only showing up for the last table.

Any suggestions?
0
 
LVL 83

Expert Comment

by:Dave Baldwin
ID: 36593582
Move that last row up to be part of the 'if' statement in line 11.  This also means that you need to copy lines 29 and 30 to the top of the page to prevent an error.
0
 

Author Comment

by:goodie069
ID: 36593623
Thanks, DaveBaldwin. That didn't add the extra row to the end of the first table - actually, it didn't seem to do anything. BUT, adding the entire section section from line 57-61 to line 11 did the trick! It's working beautifully now.

Thanks!
0
 
LVL 83

Expert Comment

by:Dave Baldwin
ID: 36593639
Cool, you're welcome.  Glad to help.
0

Featured Post

Free learning courses: Active Directory Deep Dive

Get a firm grasp on your IT environment when you learn Active Directory best practices with Veeam! Watch all, or choose any amount, of this three-part webinar series to improve your skills. From the basics to virtualization and backup, we got you covered.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Occasionally there is a need to clean table columns, especially if you have inherited legacy data. There are obviously many ways to accomplish that, including elaborate UPDATE queries with anywhere from one to numerous REPLACE functions (even within…
Composite queries are used to retrieve the results from joining multiple queries after applying any filters. UNION, INTERSECT, MINUS, and UNION ALL are some of the operators used to get certain desired results.​
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to dynamically set the form action using jQuery.

685 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question