X-Original-To: pgsql-sql@postgresql.org Received: from localhost (postgresql.org [64.49.215.8]) by postgresql.org (Postfix) with ESMTP id D6D0E474E44 for ; Fri, 7 Feb 2003 08:36:43 -0500 (EST) Received: from anchor-post-39.mail.demon.net (anchor-post-39.mail.demon.net [194.217.242.80]) by postgresql.org (Postfix) with ESMTP id 49382474E42 for ; Fri, 7 Feb 2003 08:36:43 -0500 (EST) Received: from mwynhau.demon.co.uk ([193.237.186.96] helo=mainbox.archonet.com) by anchor-post-39.mail.demon.net with esmtp (Exim 3.36 #2) id 18h8gP-0000VI-0d; Fri, 07 Feb 2003 13:36:45 +0000 Received: from localhost (localhost.localdomain [127.0.0.1]) by mainbox.archonet.com (Postfix) with ESMTP id 274BA16C30; Fri, 7 Feb 2003 13:36:44 +0000 (GMT) Received: from client.archonet.com (client.archonet.com [192.168.1.16]) by mainbox.archonet.com (Postfix) with ESMTP id 7D80116C2B; Fri, 7 Feb 2003 13:36:43 +0000 (GMT) Content-Type: text/plain; charset="iso-8859-1" From: Richard Huxton Organization: Archonet Ltd To: Gary Stainburn , Tomasz Myrta Subject: Re: efficient count/join query Date: Fri, 7 Feb 2003 13:36:40 +0000 User-Agent: KMail/1.4.3 Cc: pgsql-sql@postgresql.org References: <200302071007.28697.gary.stainburn@ringways.co.uk> <200302071209.55330.gary.stainburn@ringways.co.uk> <200302071257.48028.gary.stainburn@ringways.co.uk> In-Reply-To: <200302071257.48028.gary.stainburn@ringways.co.uk> MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Message-Id: <200302071336.40600.dev@archonet.com> X-Virus-Scanned: by AMaViS snapshot-20020531 X-Virus-Scanned: by AMaViS new-20020517 X-Archive-Number: 200302/155 X-Sequence-Number: 11553 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=20 sid,jid UNION ALL SELECT hsid,hjid,hcount FROM history; SELECT sid,jid,SUM(all_count) FROM all_counts GROUP BY sid,jid; --=20 Richard Huxton