X-Original-To: pgsql-sql-postgresql.org@localhost.postgresql.org Received: from localhost (unknown [200.46.204.144]) by svr1.postgresql.org (Postfix) with ESMTP id C24BFD1B1CD for ; Thu, 17 Jun 2004 14:48:43 -0300 (ADT) Received: from svr1.postgresql.org ([200.46.204.71]) by localhost (av.hub.org [200.46.204.144]) (amavisd-new, port 10024) with ESMTP id 61883-07 for ; Thu, 17 Jun 2004 17:48:39 +0000 (GMT) Received: from wolff.to (wolff.to [66.93.249.74]) by svr1.postgresql.org (Postfix) with SMTP id 84EAAD1B16A for ; Thu, 17 Jun 2004 14:48:22 -0300 (ADT) Received: (qmail 8061 invoked by uid 500); 17 Jun 2004 17:54:22 -0000 Date: Thu, 17 Jun 2004 12:54:22 -0500 From: Bruno Wolff III To: Interzone Cc: pgsql-sql@postgresql.org Subject: Re: Optimal query suggestion needed Message-ID: <20040617175422.GA7171@wolff.to> Mail-Followup-To: Interzone , pgsql-sql@postgresql.org References: <40D1AEB0.1010604@interzone.gr> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline In-Reply-To: <40D1AEB0.1010604@interzone.gr> User-Agent: Mutt/1.5.6i X-Virus-Scanned: by amavisd-new at hub.org X-Spam-Status: No, hits=0.0 tagged_above=0.0 required=5.0 tests= X-Spam-Level: X-Archive-Number: 200406/149 X-Sequence-Number: 18094 On Thu, Jun 17, 2004 at 14:46:08 +0000, Interzone wrote: > I want to create a view that will have: > from table t0 the elements "code", "address" and "mun" > from table t1 the elements "code" and "pname" > from table t2 the total number of elements, and the total number of > elements where avail = true, for every value t0_fk (foreign key to t0) > and t1_fk (foreigh key to t1). > > After several attempts and changes as the requirements changed, I finaly > came up with that : > > select t0.code, t0.address, t0.mun, t1.code as t1code, t1.pname > count(t2.code) as t2total, (select count(t2.code) as t2avail from t2 > where t2.avail = true and t2.t0_fk=t0.code and t2.t1_fk = t1.code) as > t2avail from t0, t1, t2 where t2.t0_fk = t0.code and t2.t1_fk=t1.code > group by t0.code, t0.address, t0.mun, t1.code, t1.pname This approach is actually pretty close. I think you just didn't pick a good way to count the avail = true rows. I think you can replace the above with: select t0.code, t0.address, t0.mun, t1.code as t1code, t1.pname count(t2.code) as t2total, count(case when t2.avail then 1 else NULL) as t2avail from t0, t1, t2 where t2.t0_fk = t0.code and t2.t1_fk=t1.code group by t0.code, t0.address, t0.mun, t1.code, t1.pname