Received: from localhost (maia-4.hub.org [200.46.204.183]) by postgresql.org (Postfix) with ESMTP id 206799FB830 for ; Mon, 14 May 2007 20:18:50 -0300 (ADT) Received: from postgresql.org ([200.46.204.71]) by localhost (mx1.hub.org [200.46.204.183]) (amavisd-maia, port 10024) with ESMTP id 99478-01 for ; Mon, 14 May 2007 20:18:47 -0300 (ADT) X-Greylist: from auto-whitelisted by SQLgrey-1.7.4 Received: from mail.polimetrix.com (mail.polimetrix.com [209.128.109.230]) by postgresql.org (Postfix) with ESMTP id 5E95F9FB5C8 for ; Mon, 14 May 2007 20:18:46 -0300 (ADT) Received: from [10.1.1.201] ([10.1.1.201]) by mail.polimetrix.com over TLS secured channel with Microsoft SMTPSVC(6.0.3790.1830); Mon, 14 May 2007 16:18:39 -0700 Message-ID: <4648EE4F.3040005@polimetrix.com> Date: Mon, 14 May 2007 16:18:39 -0700 From: Geoff Tolley User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.0.10) Gecko/20070226 CentOS/1.0.8-0.2.el4.centos SeaMonkey/1.0.8 MIME-Version: 1.0 To: Bryce Nesbitt CC: pgsql-sql@postgresql.org Subject: Re: Doing a conditional aggregate (e.g. count(*) if x=y) in postgres? References: <4648E8F1.4020609@obviously.com> In-Reply-To: <4648E8F1.4020609@obviously.com> Content-Type: text/plain; charset=UTF-8; format=flowed Content-Transfer-Encoding: 7bit X-OriginalArrivalTime: 14 May 2007 23:18:39.0497 (UTC) FILETIME=[348BC790:01C7967E] X-Virus-Scanned: Maia Mailguard 1.0.1 X-Archive-Number: 200705/114 X-Sequence-Number: 28394 Bryce Nesbitt wrote: > All; > Is there a way to get a conditional aggregate? I have this two column view: > > SELECT count(*) AS count, xx_plan.plan_name > FROM xx_membership > JOIN xx_account USING (account_id) > JOIN xx_plan USING (plan_id) > WHERE xx_membership.status = 10 > GROUP BY xx_plan.plan_name; > > And would like to add additional columns (not rows) breaking out > "status=20" and "status=30" totals. > Is this possible without a stored procedure? SELECT sum(CASE WHEN xx_membership.status = 10 THEN 1 ELSE 0 END) AS sum10, sum(CASE WHEN xx_membership.status = 20 THEN 1 ELSE 0 END) AS sum20, sum(CASE WHEN xx_membership.status = 30 THEN 1 ELSE 0 END) AS sum30, xx_plan.plan_name FROM xx_membership JOIN xx_account USING (account_id) JOIN xx_plan USING (plan_id) WHERE xx_membership.status IN (10,20,30) GROUP BY xx_plan.plan_name; You may or may not care about including the WHERE clause there depending upon its selectivity and whether there's an index for the planner to use. HTH, Geoff