Re: efficient count/join query

From: Richard Huxton <dev(at)archonet(dot)com>
To: Gary Stainburn <gary(dot)stainburn(at)ringways(dot)co(dot)uk>, Tomasz Myrta <jasiek(at)klaster(dot)net>
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: efficient count/join query
Date: 2003-02-07 13:36:40
Message-ID: 200302071336.40600.dev@archonet.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: 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

In response to

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message jose antonio leo 2003-02-07 13:49:00 prosgrees + java + trasnacciones
Previous Message Tomasz Myrta 2003-02-07 13:26:26 Re: efficient count/join query