Re: efficient count/join query - Mailing list pgsql-sql

From Richard Huxton
Subject Re: efficient count/join query
Date
Msg-id 200302071336.40600.dev@archonet.com
Whole thread Raw
In response to Re: efficient count/join query  (Gary Stainburn <gary.stainburn@ringways.co.uk>)
Responses prosgrees + java + trasnacciones  ("jose antonio leo" <jaleo8@storelandia.com>)
List pgsql-sql
On Friday 07 Feb 2003 12:57 pm, Gary Stainburn wrote:
>
> Thinking about it, I'm not wanting to perform a join as such, but a merge
> of the two selects below, then some form of group by to sum() the two
> counts.
>
>     select rosid as sid, rojid as jid, count(*) as count
>                   from roster group by sid, jid order by sid, jid;
>     select hsid as sid, hjid as jid, hcount as count
>                   from history order by sid, jid;
>
> so that
>
> 1    2    1
> 1    3    2
>
> and
>
> 1    3    1
> 1    4    2
>
> becomes
>
> 1    2    1
> 1    3    3
> 1    4    2

You want a UNION, something like (untested):

CREATE VIEW all_counts AS
SELECT rosid as sid, rojid as jid, count(*) as all_count FROM roster GROUP BY
sid,jid
UNION ALL
SELECT hsid,hjid,hcount FROM history;

SELECT sid,jid,SUM(all_count) FROM all_counts GROUP BY sid,jid;

--  Richard Huxton


pgsql-sql by date:

Previous
From: Tomasz Myrta
Date:
Subject: Re: efficient count/join query
Next
From: "jose antonio leo"
Date:
Subject: prosgrees + java + trasnacciones