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? 4 4861
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.
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.
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.
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. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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.
|
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...
|
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...
|
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?
|
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.
| |
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...
|
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.
|
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)...
|
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;
|
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...
|
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...
| |
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...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
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...
| |