From: Sam Mason <sam@samason.me.uk>
To: pgsql-general@postgresql.org
Subject: Re: combine SQL SELECT statements into one
Date: Mon, 1 Feb 2010 12:08:49 +0000
Message-ID: <20100201120849.GZ5407@samason.me.uk> (raw)
In-Reply-To: <995516.81823.qm@web113717.mail.gq1.yahoo.com>
References: <995516.81823.qm@web113717.mail.gq1.yahoo.com>
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/
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Reply to all the recipients using the --to and --cc options:
reply via email
To: pgsql-sql@postgresql.org
Cc: sam@samason.me.uk, pgsql-general@postgresql.org
Subject: Re: combine SQL SELECT statements into one
In-Reply-To: <20100201120849.GZ5407@samason.me.uk>
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox