Received: from maia.hub.org (unknown [200.46.204.183]) by mail.postgresql.org (Postfix) with ESMTP id 5CDB0632EA4 for ; Mon, 1 Feb 2010 08:09:05 -0400 (AST) Received: from mail.postgresql.org ([200.46.204.86]) by maia.hub.org (mx1.hub.org [200.46.204.183]) (amavisd-maia, port 10024) with ESMTP id 66210-10 for ; Mon, 1 Feb 2010 12:08:54 +0000 (UTC) X-Greylist: from auto-whitelisted by SQLgrey-1.7.6 Received: from frubble.xen.chris-lamb.co.uk (frubble.xen.chris-lamb.co.uk [89.16.166.12]) by mail.postgresql.org (Postfix) with ESMTP id E29FD63249E for ; Mon, 1 Feb 2010 08:08:53 -0400 (AST) Received: from sam by frubble.xen.chris-lamb.co.uk with local (Exim 4.63) (envelope-from ) id 1Nbv5F-00054J-VO for pgsql-general@postgresql.org; Mon, 01 Feb 2010 12:08:50 +0000 Date: Mon, 1 Feb 2010 12:08:49 +0000 From: Sam Mason To: pgsql-general@postgresql.org Subject: Re: combine SQL SELECT statements into one Message-ID: <20100201120849.GZ5407@samason.me.uk> References: <995516.81823.qm@web113717.mail.gq1.yahoo.com> MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline In-Reply-To: <995516.81823.qm@web113717.mail.gq1.yahoo.com> User-Agent: Mutt/1.5.13 (2006-08-11) X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=-2.599 tagged_above=-10 required=5 tests=BAYES_00=-2.599 X-Spam-Level: X-Archive-Number: 201002/14 X-Sequence-Number: 158790 On Sun, Jan 31, 2010 at 11:36:55PM -0800, Neil Stlyz wrote: > SELECT COUNT(distinct model) FROM inventory WHERE modified >= '2010-02-01'; > SELECT COUNT(distinct model) FROM inventory WHERE modified >= '2010-01-20'; > SELECT COUNT(distinct model) FROM inventory WHERE modified >= '2010-01-01'; > > All three of the above queries work and provide results. However, > I want to combine the three into one SQL Statement that hits the > database one time. How can I do this in one SQL Statement? Is it > possible with sub select? If you only wanted a single table scan, you could use CASE: SELECT COUNT(DISTINCT CASE WHEN modified >= '2010-02-01' THEN model END) AS c1, COUNT(DISTINCT CASE WHEN modified >= '2010-01-20' THEN model END) AS c2, COUNT(DISTINCT CASE WHEN modified >= '2010-01-01' THEN model END) AS c3 FROM inventory WHERE modified >= '2010-01-01'; Note that the final WHERE clause isn't really needed, it'll just make things a bit faster and give PG the opportunity to use an INDEX if it looks helpful. If you're generating the above from code, you may want to use the LEAST function in SQL rather than working out the smallest value in your code, i.e: WHERE modified >= LEAST('2010-02-01','2010-02-01','2010-02-01'); -- Sam http://samason.me.uk/