Received: from echna.ne.jp (echna.ne.jp [210.175.52.4]) by postgresql.org (8.11.3/8.11.4) with ESMTP id g04FHvm64284 for ; Fri, 4 Jan 2002 10:17:58 -0500 (EST) (envelope-from rk73@echna.ne.jp) Received: from VIP333 [210.175.55.138] by echna.ne.jp with ESMTP (SMTPD32-6.06) id A7911081003A; Sat, 05 Jan 2002 00:17:37 +0900 Date: Sat, 05 Jan 2002 00:18:46 +0900 From: Masaru Sugawara To: aannddrree@libero.it (andrea) Subject: Re: left join and where Cc: pgsql-sql@postgresql.org In-Reply-To: References: Errors-To: Message-Id: <20020104211134.4181.RK73@echna.ne.jp> MIME-Version: 1.0 Content-Type: text/plain; charset="US-ASCII" Content-Transfer-Encoding: 7bit X-Mailer: Becky! ver. 2.00.08 X-Archive-Number: 200201/34 X-Sequence-Number: 6125 On 27 Dec 2001 12:28:43 -0800 aannddrree@libero.it (andrea) wrote: > I'm a beginner and I have a trouble with SQL and Access 97 > I try to explain the problem: > > I have a table colori: > > ID colore > 1 red > 2 blu > 3 green > > and a table Vendite > > ID colore anno quantita > 1 red 1 10 > 2 blu 1 20 > 3 green 2 30 > > I want a query that return all "quantita" but only for a year (for example > if year =1, I don't extarct green) > The result must be: > > colore anno quantita > red 1 10 > blu 1 20 > green > ------------------------------------ > > I use this SQL code > > SELECT colori.colore, vendite.anno, sum(vendite.quantita) > FROM colori > LEFT JOIN vendite ON colori.colore=vendite.colore > WHERE vendite.anno=1 OR vendite.anno Is Null > GROUP BY colori.colore, vendite.anno > > But the result is > > colore anno quantita > red 1 10 > blu 1 20 > > How can I get the correct result Since most of DB software's support subqueries (not to mention, also Access 97), the following query could get what you would expect. Since, however, the table of Vendite has very small example, I'm not sure whether "v0.anno IS NULL" that I cite from yours is actually needed or not. SELECT c1.colore, v1.anno, SUM(v1.quantita) AS quantita FROM colori AS c1 LEFT JOIN (SELECT v0.* FROM vendite AS v0 WHERE v0.anno = 1 OR v0.anno IS NULL) AS v1 ON c1.colore = v1.colore GROUP BY c1.colore, v1.anno ; In case of no using subqueries, here is: SELECT c0.colore, v0.anno, Sum(v0.quantita) AS quantita FROM colori AS c0 LEFT JOIN vendite AS v0 ON c0.colore = v0.colore WHERE v0.anno = 1 OR v0.anno IS NULL GROUP BY c0.colore, v0.anno UNION SELECT c1.colore, NULL, NULL FROM colori AS c1 LEFT JOIN vendite AS v1 ON c1.colore = v1.colore WHERE v1.anno > 1 ; Regards, Masaru Sugawara