Re: Join 2 aggregate queries?

From: "scott(dot)marlowe" <scott(dot)marlowe(at)ihs(dot)com>
To: Zak McGregor <zak(at)mighty(dot)co(dot)za>
Cc: <pgsql-general(at)postgresql(dot)org>
Subject: Re: Join 2 aggregate queries?
Date: 2004-02-13 16:00:29
Message-ID: Pine.LNX.4.33.0402130858480.9564-100000@css120.ihs.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Fri, 13 Feb 2004, Zak McGregor wrote:

> Hi all
>
>
> I have 2 aggregate queries, which are:
>
> select f.id as fixtureid, t.name as home_team, count(t.name)
> from teams t, results r, fixtures f, playerstoteams p
> where f.type=1 and f.league=4 and r.fixture=f.id and t.division=4
> and p.teamid=t.id and r.home=p.playerid and r.winner=p.playerid
> group by fixtureid, t.name;
>
>
> fixtureid | home_team | count
> -----------+-----------+-------
> 2872 | Kat Fish | 12
> 2944 | The Fowls | 11
>
> and
>
> select f.id as fixtureid, t.name as away_team, count(t.name)
> from teams t, results r, fixtures f, playerstoteams p
> where f.type=1 and f.league=4 and r.fixture=f.id and t.division=4
> and p.teamid=t.id and r.away=p.playerid and r.winner=p.playerid
> group by fixtureid, t.name;
>
> fixtureid | away_team | count
> -----------+-------------+-------
> 2872 | A Cut Above | 13
> 2944 | Kat Fish | 14
>
> I'd like to join them somehow to get the following:
>
> fixtureid | home_team | count1 | away_team | count2
> -----------+-----------+--------+-------------+-------
> 2872 | Kat Fish | 12 | A Cut Above | 13
> 2944 | The Fowls | 11 | Kat Fish | 14

Sure, make each a subselect and join those:

select * from

(select f.id as fixtureid, t.name as home_team, count(t.name)
from teams t, results r, fixtures f, playerstoteams p
where f.type=1 and f.league=4 and r.fixture=f.id and t.division=4
and p.teamid=t.id and r.home=p.playerid and r.winner=p.playerid
group by fixtureid, t.name) as a

join

(select f.id as fixtureid, t.name as away_team, count(t.name)
from teams t, results r, fixtures f, playerstoteams p
where f.type=1 and f.league=4 and r.fixture=f.id and t.division=4
and p.teamid=t.id and r.away=p.playerid and r.winner=p.playerid
group by fixtureid, t.name) as b

on (a.id=b.id);

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Andrew Sullivan 2004-02-13 16:24:05 Re: Quad Xeon vs. Dual Itanium
Previous Message Froggy / Froggy Corp. 2004-02-13 15:30:03 Too much CPU usage