Received: from localhost.localdomain (postgresql.org [64.49.215.8]) by localhost (Postfix) with ESMTP id A6DA9475AAE for ; Sun, 7 Jul 2002 16:25:32 -0400 (EDT) Mailbox-Line: From roy@silicontao.com Sun Jul 7 16:25:32 2002 Received: from priv-edtnes28.telusplanet.net (defout.telus.net [199.185.220.240]) by postgresql.org (Postfix) with ESMTP id 5D9F34759AD for ; Sun, 7 Jul 2002 16:25:31 -0400 (EDT) Received: from UtopiaPlanetia ([142.179.175.121]) by priv-edtnes28.telusplanet.net (InterMail vM.5.01.04.05 201-253-122-122-105-20011231) with ESMTP id <20020707202531.TYXT25741.priv-edtnes28.telusplanet.net@UtopiaPlanetia> for ; Sun, 7 Jul 2002 14:25:31 -0600 Content-Type: text/plain; charset="us-ascii" From: Roy Souther Reply-To: Roy Souther Organization: Silicon Tao Technology Systems To: pgsql-sql@postgresql.org Subject: Bad SUM result Date: Sun, 7 Jul 2002 14:25:51 -0600 X-Mailer: KMail [version 1.4] MIME-Version: 1.0 Content-Transfer-Encoding: 8bit Message-Id: <200207071425.56235.roy@silicontao.com> X-Spam-Status: No, hits=-2.0 required=5.0 tests=DOUBLE_CAPSWORD,PGP_SIGNATURE version=2.30 X-Spam-Level: X-Archive-Number: 200207/80 X-Sequence-Number: 8459 -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 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. 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. - -- Roy Souther http://www.SiliconTao.com Linux: May the source be with you. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAj0oo9MACgkQCbnxcmEBt43qFQCgtjCs7khKGH+2LYd78O9mA3h4 vDQAn0GkKkuYl1Kybgm/ITO4LbO1WWLX =1G4R -----END PGP SIGNATURE-----