Received: from news.tht.net (news.hub.org [216.126.91.242]) by postgresql.org (8.11.3/8.11.4) with ESMTP id f8CAJZ708361 for ; Wed, 12 Sep 2001 06:19:35 -0400 (EDT) (envelope-from news@news.tht.net) Received: (from news@localhost) by news.tht.net (8.11.4/8.11.4) id f8CAIaT05156 for pgsql-sql@postgresql.org; Wed, 12 Sep 2001 06:18:36 -0400 (EDT) (envelope-from news) From: yaubi@yaubi.com (Yoann) X-Newsgroups: comp.database.ms-access, comp.database.oracle, comp.databases.postgresql.sql, comp.databases.sybase, comp.databases Subject: Re: Combine query views into one SQL string Date: 12 Sep 2001 03:18:35 -0700 Organization: http://groups.google.com/ Lines: 58 Message-ID: <70c8063b.0109120218.20505f00@posting.google.com> References: <63e57aa8.0109060835.33719290@posting.google.com> <3B97DC1F.94433F65@mbit.nl> <9na15r$ku4$1@narses.hrz.tu-chemnitz.de> <63e57aa8.0109091520.4f975abd@posting.google.com> Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 8bit X-Complaints-To: groups-abuse@google.com To: pgsql-sql@postgresql.org X-Archive-Number: 200109/81 X-Sequence-Number: 4734 eimas@lycos.com (Eimas) wrote in message news:<63e57aa8.0109091520.4f975abd@posting.google.com>... > "Maik" wrote in message news:<9na15r$ku4$1@narses.hrz.tu-chemnitz.de>... > > Its clear, union concat the two results. > > > > But he can also use this join version, if its the intention. > > > > select t1.id, sum(t1.amount), t2.id, sum(t2.amount) from table1 as t1, > > table2 as t2 where t1.id=t2.id; > > > > Ciao Maik > > This is not right, i wouldnt even bather you if this was the simple > answer. > > t1.id=t2.id would mean in doubled or tripled aggregation, > since t1.id and t2.id are not unique, thats why I had to aggregate > them in first Q1, Q2 querires, and link them by ID in the last one. > > I don't understand what UNION got to do here. then you probably have > to make three union links of inner, left and right joined tables. > > This is not that easy as it seems. > Is there a universal SQL string "expanding" rules, like in math or so? > > Thanks Hi, I think a got it. Just try : SELECT DISTINCT t.ID, (SELECT SUM(amount) FROM Table1 WHERE ID = t.ID), (SELECT SUM(amount) FROM Table2 WHERE ID = t.ID) FROM Table1 AS t UNION SELECT DISTINCT t.ID, (SELECT SUM(amount) FROM Table1 WHERE ID = t.ID), (SELECT SUM(amount) FROM Table2 WHERE ID = t.ID) FROM Table2 AS t; There are in fact two queries : one scaning for the ID's from Table1 and the other from Table2 in order to calcutate the sums for ALL the ID's. For each scaned ID, it calculates the corresponding sum in each of the two tables. If the ID doesn't exist in one table, the sum return a Null value, but doesn't affect the other. I hope this query is what you are looking for. Yoann