Solved

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

Posted on 2011-09-24
9
297 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
 
LVL 82

Accepted Solution

by:
Dave Baldwin earned 500 total points
Comment Utility
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
Backup Your Microsoft Windows Server®

Backup all your Microsoft Windows Server – on-premises, in remote locations, in private and hybrid clouds. Your entire Windows Server will be backed up in one easy step with patented, block-level disk imaging. We achieve RTOs (recovery time objectives) as low as 15 seconds.

 

Author Comment

by:goodie069
Comment Utility
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
Comment Utility
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 82

Expert Comment

by:Dave Baldwin
Comment Utility
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
Comment Utility
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 82

Expert Comment

by:Dave Baldwin
Comment Utility
Cool, you're welcome.  Glad to help.
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

If you have heard of RFC822 date formats, they can be quite a challenge in SQL Server. RFC822 is an Internet standard format for email message headers, including all dates within those headers. The RFC822 protocols are available in detail at:   ht…
Does the idea of dealing with bits scare or confuse you? Does it seem like a waste of time in an age where we all have terabytes of storage? If so, you're missing out on one of the core tools in every professional programmer's toolbox. Learn how to …
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

728 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

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now