473,603 Members | 2,638 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Calculating totals from two tables

Hopefully someone can help me create a query that I'm having some
trouble with.

I have three tables: invoices, invoicedetails, invoicepayments

The fields are:

invoices
--------
InvoiceNo
InvoiceDate
CompanyNo

invoicedetails
--------------
InvoiceNo
ProductNo
Quantity
UnitPrice

invoicepayments
---------------
InvoiceNo
PaymentDate
PaymentAmount

For each row in invoices there will be 0 or more rows in
invoicedetails and invoicepayments , with the InvoiceNo field linking
everything together (i.e. one to many relationship between invoices
and invoicedetails and invoicepayments ).

I need a query that will give me a list of invoices that still have
money outstanding on them.

To manually do this I would loop through the invoices table and for
each InvoiceNo I would gather all the matching rows in invoicedetails
and invoicepayments . To get the invoice total I would multiply
Quantity by UnitPrice for each invoicedetails row. To get the total
paid I would add up the PaymentAmount. Then I'd compare the invoice
total and the payment total and if the payment total was less than the
invoice total I'd know that there was still some money outstanding on
that invoice.

Now, how do I write a single query to do this? I using MySQL 4.0.20
(unfortunately because I don't control the server I can't upgrade to a
version of MySQL that support subqueries). I'm guessing I'll need to
use the SUM() function to add things up, and GROUP BY to group the
invoicedetails and invoicepayments so I only get one row per invoice.

I can get a total for each invoice by using the following query:

SELECT invoices.Invoic eNo, SUM(Quantity * UnitPrice) AS InvTotal
FROM invoices, invoicedetails
WHERE invoices.Invoic eNo = invoicedetails. InvoiceNo
GROUP BY invoices.Invoic eNo

However I'm at a loss as to how I would modify this query to also
total up the invoicepayments to give me a PaymentsTotal and then
calculate the difference between the InvTotal and the PaymentsTotal to
figure out if there is still money outstanding.

Can anyone help me out or point me in the right direction?
Jul 20 '05 #1
4 4844
The Bit Bandit wrote:
Can anyone help me out or point me in the right direction?


I think this might help. One part I'm unsure of (without testing it) is
whether one can use a derived column name in the HAVING clause.

SELECT i.InvoiceNo, SUM(d.Quantity * d.UnitPrice) AS InvTotal,
SUM(d.Quantity * d.UnitPrice) - SUM(p.PaymentAm ount) AS
InvRemainingBal ance
FROM invoices i INNER JOIN invoicedetails d ON (i.InvoiceNo = d.InvoiceNo)
LEFT OUTER JOIN invoicepayments p ON (i.InvoiceNo = p.InvoiceNo)
HAVING InvRemainingBal ance > 0
GROUP BY i.InvoiceNo

Regards,
Bill K.
Jul 20 '05 #2
Many thanks for your help, Bill. Your advice is greatfully received!

It looks like you can't use a derived column name in the HAVING
clause. When I tried it I got the following error:

#1064 - You have an error in your SQL syntax near 'GROUP BY
i.InvoiceNo'

I'm assuming the error message is referring to the HAVING clause,
which is immediately before the GROUP BY clause.

I tried simplifying the query to see just the totals (i.e. not working
out the difference to get the amount outstanding) and the query looks
like this:

SELECT i.InvoiceNo, SUM(d.Quantity * d.UnitPrice) AS InvTotal,
SUM(p.PaymentAm ount) AS InvRemainingBal ance
FROM invoices i
INNER JOIN invoicedetails d ON (i.InvoiceNo = d.InvoiceNo)
LEFT OUTER JOIN invoicepayments p ON (i.InvoiceNo = p.InvoiceNo)
GROUP BY i.InvoiceNo

I notice that for this query the total payments is being calculated
incorrectly. For example I have one invoice with 11 detail lines that
total up to 5136.86. This invoice has a single payment of 5136.86,
but the query is telling me that the total payments for this invoice
is 56505.46 (which just happens to be the total for the invoice
multiplied by the number of detail lines).

It's as if MySQL is expecting the number of invoicepayments records to
be the same as the number of invoicedetails for any particular
invoice, and because it isn't it's repeating the amounts.

Any ideas on how to fix this?
Bill Karwin <bi**@karwin.co m> wrote in message news:<cl******* **@enews4.newsg uy.com>...
The Bit Bandit wrote:
Can anyone help me out or point me in the right direction?


I think this might help. One part I'm unsure of (without testing it) is
whether one can use a derived column name in the HAVING clause.

SELECT i.InvoiceNo, SUM(d.Quantity * d.UnitPrice) AS InvTotal,
SUM(d.Quantity * d.UnitPrice) - SUM(p.PaymentAm ount) AS
InvRemainingBal ance
FROM invoices i INNER JOIN invoicedetails d ON (i.InvoiceNo = d.InvoiceNo)
LEFT OUTER JOIN invoicepayments p ON (i.InvoiceNo = p.InvoiceNo)
HAVING InvRemainingBal ance > 0
GROUP BY i.InvoiceNo

Regards,
Bill K.

Jul 20 '05 #3
The Bit Bandit wrote:
It's as if MySQL is expecting the number of invoicepayments records to
be the same as the number of invoicedetails for any particular
invoice, and because it isn't it's repeating the amounts.
Yes, I see why it's doing that. The inner join between invoices and
invoicedetails is a multi-line result set, and for each of those lines,
it repeats the invoicepayment. Mea culpa! I should have noticed this
when I gave the suggested query.
Any ideas on how to fix this?


Try this:
SELECT i.InvoiceNo, SUM(d.Quantity * d.UnitPrice) AS InvTotal,
SUM(p.PaymentAm ount) / COUNT(d.Invoice No) AS InvRemainingBal ance
....

But this seems like a pretty ugly hack to me, even though it may give
the correct result. It's not very maintainable!

The other solution I can think of is that you'd have to calculate the
InvTotal and InvRemainingBal ance in separate queries. That would
require recombining the results in your application, but it would be
much clearer code and more maintainable.

You might have more options when you can use MySQL 4.1 with subqueries.

Regards,
Bill K.
Jul 20 '05 #4
Thanks again, Bill, for your great help.

I'm thinking that it may well be easier to add a new field to the
invoices table that flags whether the invoice has been paid in full or
not. Then in my app when payments are being entered I can easily
figure out if the invoice has been fully paid for and if so set the
flag. Then it's just a simple matter of selecting the invoices that
don't have the flag set.

I know this kind of goes against data normalisation rules, but it will
certainly be easier!

Thank you very much for all your help, I've certainly learned a thing
or two about MySQL.

Bill Karwin <bi**@karwin.co m> wrote in message news:<cl******* **@enews3.newsg uy.com>...
The Bit Bandit wrote:
It's as if MySQL is expecting the number of invoicepayments records to
be the same as the number of invoicedetails for any particular
invoice, and because it isn't it's repeating the amounts.


Yes, I see why it's doing that. The inner join between invoices and
invoicedetails is a multi-line result set, and for each of those lines,
it repeats the invoicepayment. Mea culpa! I should have noticed this
when I gave the suggested query.
Any ideas on how to fix this?


Try this:
SELECT i.InvoiceNo, SUM(d.Quantity * d.UnitPrice) AS InvTotal,
SUM(p.PaymentAm ount) / COUNT(d.Invoice No) AS InvRemainingBal ance
...

But this seems like a pretty ugly hack to me, even though it may give
the correct result. It's not very maintainable!

The other solution I can think of is that you'd have to calculate the
InvTotal and InvRemainingBal ance in separate queries. That would
require recombining the results in your application, but it would be
much clearer code and more maintainable.

You might have more options when you can use MySQL 4.1 with subqueries.

Regards,
Bill K.

Jul 20 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

13
2382
by: | last post by:
I have an Access database used to track donor pledges. In it, there is a table that contains three fields for each donor: Gift_Amount, Gift_Per_Year, and Matching_Gift_Ratio. The following formula would calculate the total pledge amount for each donor: (Gift_Amount * Gift_Per_Year) * (Matching_Gift_Ratio + 1). A total Pledge for all donors would just sum up the calculated values.
3
1649
by: Paul Mendez | last post by:
Performance_Date SumOfBudget_NOI CurrYTD_BudgetNOI_Total 1/1/2004 $4,184,626.00 ? 2/1/2004 $4,484,710.00 ? 3/1/2004 $4,537,424.00 ? 4/1/2004 $4,826,850.00 ? 5/1/2004 $4,966,326.00 ? Can someone help? What I am trying to do is create a query that will end up looking like the bottom example. The above query is a calculated totals query with an...
1
2504
by: Megan | last post by:
quick summary: i'm having problems trying to group fields in a report in order to calculate percentages. to calculate percentages, i'm comparing the results from my grouped fields to the totals. first, let me say that this is a really long post. i wasn't sure how much information/ background to provide, so i thought more was better than less. i tried to delineate certain areas so that it would be easy to peruse my posting and find...
2
35879
by: mhodkin | last post by:
I created a query in which I have grouped data by City. I wish to calculate the percent of each value, e.g. City/(Total count of all Cities), in tbe next column of the query. I can't seem to write the correct expression due to the "groupby" needed to group the city count in the first column. Any clues?
4
3392
by: New Guy | last post by:
I'm trying to work with a system that somebody else built and I am confounded by the following problem: There is a table of payments and a table of charges. Each client has charges and payments during the month. I'd like to get the totals of the payments and of the charges for each client. When I run the following query, I get huge numbers that appear as if the join is not working correctly.
0
1941
by: Zlatko Matić | last post by:
I have experienced some problems with total operations (sum, min, max, avg etc) in pivot tables nad pivot charts in .mde. In .mdb I can activate any totals operation. on both notebook and desktop PC. When I create .mde on the notebook, I can use totals on laptop, but not on the desktop PC. I just can't switch on any total. There is no total operation in the menu... If I create .mde on the desktop PC then it works....In both cases it is...
2
2299
by: Tim Marshall | last post by:
Wondering if anyone has any suggestions for this. Sometimes in the form reports my users run, a data sheet subform on a main form, with totals in text boxes with calculated controlsources (=sum(whatever)), the records returned are large. By "large" I mean that there is a significant lag time before the totals get calculated and display. Lag time and what constitutes "large" varies with the user's PC hardware/configuration.
2
1868
by: mtchampi | last post by:
Hello all, I have a limited SQL background, and I am responsible for creating a monthly report that displays separate tables for the following: 1. Calculate individual monthly totals of files processed (created) that month 2. Accumulating totals per month, (eg. Jan 200 files, Feb 300 files, so Feb would now read as 500 files) 3. Take a constant number, say 10,000 records, subtract the year to date result(from the accummulating totals)...
38
9104
by: d0ugg | last post by:
I'm writing a program that will have to roll the dice A and dice B one million times, and calculate the percentage of times that the dies will be equal. I'm having trouble to figure out how the percentage will work. Here is my code: #include <ctime> #include <iostream> using namespace std;
0
7928
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8405
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8060
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8273
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6735
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
3951
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2430
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1514
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1259
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.