Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

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

Posted on 2011-09-24
9
Medium Priority
?
306 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Prepare for your VMware VCP6-DCV exam.

Josh Coen and Jason Langer have prepared the latest edition of VCP study guide. Both authors have been working in the IT field for more than a decade, and both hold VMware certifications. This 163-page guide covers all 10 of the exam blueprint sections.

 
LVL 84

Accepted Solution

by:
Dave Baldwin earned 2000 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 84

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 84

Expert Comment

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

Featured Post

NEW Veeam Agent for Microsoft Windows

Backup and recover physical and cloud-based servers and workstations, as well as endpoint devices that belong to remote users. Avoid downtime and data loss quickly and easily for Windows-based physical or public cloud-based workloads!

Question has a verified solution.

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

This post contains step-by-step instructions for setting up alerting in Percona Monitoring and Management (PMM) using Grafana.
There are times when I have encountered the need to decompress a response from a PHP request. This is how it's done, but you must have control of the request and you can set the Accept-Encoding header.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
In this video, Percona Solutions Engineer Barrett Chambers discusses some of the basic syntax differences between MySQL and MongoDB. To learn more check out our webinar on MongoDB administration for MySQL DBA: https://www.percona.com/resources/we…

715 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