Full outer join question. - Mailing list pgsql-general

From Paul McGarry
Subject Full outer join question.
Date
Msg-id a056b1d4050707182243b540dc@mail.gmail.com
Whole thread Raw
Responses Joins with aggregate data
Re: Full outer join question.
List pgsql-general
Hi there everyone,

I'm having trouble getting the rows I want from a full outer join with
a where clause. Here is a simplified version of my tables:

======
create table lefty (
 day date,
 goodamount numeric(10,2),
 grp integer
);

insert into lefty values ('2005-06-01',5.00,1);
insert into lefty values ('2005-06-02',10.00,1);
insert into lefty values ('2005-06-01',2.50,2);


create table righty (
 day date,
 badamount numeric(10,2),
 grp integer
);

insert into righty values ('2005-06-01',-5.00,3);
insert into righty values ('2005-06-02',-10.00,1);
insert into righty values ('2005-06-02',-2.50,1);
======

The base query I want to do is:
SELECT grp, count(goodamount), sum(goodamount), count(badamount),
sum(badamount) FROM lefty FULL OUTER JOIN righty USING (grp) GROUP BY
grp;

This returns what I expect:
======
 grp | count |  sum  | count |  sum
-----+-------+-------+-------+--------
   3 |     0 |       |     1 |  -5.00
   2 |     1 |  2.50 |     0 |
   1 |     4 | 30.00 |     4 | -25.00
======

However, in the real world I don't want to do a query for the entire
tables, but for a particular date period, ie add restraints on
lefty.day and righty.day.

When I do that I lose all the rows whose grp isn't in both tables. For example:
======
SELECT grp, count(goodamount), sum(goodamount), count(badamount),
sum(badamount) FROM lefty FULL OUTER JOIN righty USING (grp)
WHERE lefty.day >= '2005-06-01' AND righty.day>='2005-06-01'
GROUP BY grp;
 grp | count |  sum  | count |  sum
-----+-------+-------+-------+--------
   1 |     4 | 30.00 |     4 | -25.00
======

Any ideas?

Paul

pgsql-general by date:

Previous
From: David Gagnon
Date:
Subject: Postgresql is not able to find a stored procedure with a smallint instead of integer in signature
Next
From: Paul McGarry
Date:
Subject: Joins with aggregate data