🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: borland.public.interbase.sql
Article #423

Sum two tables with HAVING

#423
From: P.G. Willemsen
Date: Fri, 07 Mar 2008 16:10
40 lines
1796 bytes
I would like to get sums from two tables like this:

select
   t1.id, t1.description,
   (select sum(t2.amount) from t2 where t2.id = t1.id) as sum1,
   (select sum(t3.amount) from t3 where t3.id = t1.id) as sum2
from t1

with a condition to eliminate all rows with zeroes:

where sum1 <> 0 and sum2 <> 0 --> doesn't work
*or*
having sum1 <> 0 and sum2 <> 0 --> doesn't work


How could I prevent getting rows with zeroes?


I also tried rewriting the query like this:

select
   t1.id, t1.description,
   sum(t2.amount) as sum1,
   sum(t3.amount) as sum2
from t2
   left join t1 on t1.id = t2.id
   left join t3 on t3.id = t2.id
group by
   t1.id, t1.description
having
   sum(t2.amount) <> 0 and sum(t3.amount) <> 0

This eliminates all rows with double zeroes, but all sums are twice as 
high, because of the double joins, so all rows are twice in the joined 
set that is summed.

Who can help me to get the correct query?

Thanks in advance!
Peter
Technical Details
Message-ID: <47d1690f$1@newsgroups.borland.com>
Path: arc1-ca.pugleaf.net!g2news1.google.com!news2.google.com!news1.google.com!news.glorb.com!newsfeeds.ihug.co.nz!ihug.co.nz!newsgroups.borland.com!not-for-mail

Show Full Headers
Complete Article Headers
X-Google-Thread: 114a0e,1e4b593392602380,start
X-Google-Attributes: gid114a0e,public,usenet
X-Google-Language: ENGLISH,ASCII-7-bit
Date: Fri, 07 Mar 2008 17:10:55 +0100
From: "P.G. Willemsen" <peter@remove.this.vhep.and.this.nl>
User-Agent: Thunderbird 2.0.0.12 (Windows/20080213)
MIME-Version: 1.0
Newsgroups: borland.public.interbase.sql
Subject: Sum two tables with HAVING
Content-Type: text/plain; charset=ISO-8859-1; format=flowed
Content-Transfer-Encoding: 7bit
NNTP-Posting-Host: 83.85.252.219
Message-ID: <47d1690f$1@newsgroups.borland.com>
X-Trace: newsgroups.borland.com 1204906255 83.85.252.219 (7 Mar 2008 08:10:55 -0700)
Lines: 40
Path: arc1-ca.pugleaf.net!g2news1.google.com!news2.google.com!news1.google.com!news.glorb.com!newsfeeds.ihug.co.nz!ihug.co.nz!newsgroups.borland.com!not-for-mail