Re: left join and where

From: Masaru Sugawara <rk73(at)echna(dot)ne(dot)jp>
To: aannddrree(at)libero(dot)it (andrea)
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: left join and where
Date: 2002-01-04 15:18:46
Message-ID: 20020104211134.4181.RK73@echna.ne.jp
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

On 27 Dec 2001 12:28:43 -0800
aannddrree(at)libero(dot)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

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Andrew Perrin 2002-01-04 16:29:37 Telling how many records are joined
Previous Message Unnikrishnan Menon 2002-01-04 14:55:58 Execute dynamically generated query???