Received: from localhost.localdomain (postgresql.org [64.49.215.8]) by localhost (Postfix) with ESMTP id 0A622475CB8 for ; Sun, 7 Jul 2002 16:45:03 -0400 (EDT) Mailbox-Line: From sszabo@megazone23.bigpanda.com Sun Jul 7 16:45:03 2002 Received: from megazone.bigpanda.com (megazone.bigpanda.com [63.150.15.178]) by postgresql.org (Postfix) with ESMTP id A02EF475AAE for ; Sun, 7 Jul 2002 16:44:53 -0400 (EDT) Received: by megazone.bigpanda.com (Postfix, from userid 1001) id C1101D605; Sun, 7 Jul 2002 13:44:54 -0700 (PDT) Received: from localhost (localhost [127.0.0.1]) by megazone.bigpanda.com (Postfix) with ESMTP id B6C375C03; Sun, 7 Jul 2002 13:44:54 -0700 (PDT) Date: Sun, 7 Jul 2002 13:44:54 -0700 (PDT) From: Stephan Szabo To: Roy Souther Cc: Subject: Re: Bad SUM result In-Reply-To: <200207071425.56235.roy@silicontao.com> Message-ID: <20020707133824.L19117-100000@megazone23.bigpanda.com> MIME-Version: 1.0 Content-Type: TEXT/PLAIN; charset=US-ASCII X-Spam-Status: No, hits=-2.4 required=5.0 tests=IN_REP_TO,X_NOT_PRESENT,DOUBLE_CAPSWORD,NO_MX_FOR_FROM version=2.30 X-Spam-Level: X-Archive-Number: 200207/81 X-Sequence-Number: 8460 On Sun, 7 Jul 2002, Roy Souther wrote: > I have an invoice database that has two tables one for invoices and one for > payments. I want to get the account balance for a client by subtracting the > sum of all payments from the sum off all invoices for that client. > > Here is the SQL that I thought should work. > SELECT SUM(t0.totalprice)-SUM(t1.paymentamount) FROM invoices t0, payments t1 > WHERE t0.custnumber='1' AND t1.custnumber='1' > > It works fine if there is only one invoice and one payment but as soon as > there is more then one of either it screws up. For each match found in > payments the invoice sum is added to the total. So if client 1 purchased a > $100 item then maid a $10 payment the SQL would return the balance of $90 > just fine. When the client makes a second payment of $15 the balance is $75 > but this SQL returns ($100+$100)-($10+$15) = $175. A third payment of $1 > would return ($100+$100+$100)-($10+$15+$1) = $274. Right, because you're doing a join that ends up with 100 | 10 100 | 15 100 | 1 as the effective rows. > Could some one explain this to me and recommend an SQL command that would work > please? I could do this using a temp table but that would be very messy as I > would really like it to be a single SQL command. Maybe something like: select sum(amt) from (select custnumber, totalprice as amt from invoices union select custnumber, -paymentamount as amt from payments) as c where custnumber='1';