Solved

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

Posted on 2011-09-24
9
301 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
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.

 
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

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

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

Build an array called $myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
This article describes how to use the timestamp of existing data in a database to allow Tableau to calculate the prior work day instead of relying on case statements or if statements to calculate the days of the week.
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

776 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