From: | Sam Mason <sam(at)samason(dot)me(dot)uk> |
---|---|
To: | pgsql-general(at)postgresql(dot)org |
Subject: | Re: combine SQL SELECT statements into one |
Date: | 2010-02-01 12:08:49 |
Message-ID: | 20100201120849.GZ5407@samason.me.uk |
Views: | Raw Message | Whole Thread | Download mbox | Resend email |
Thread: | |
Lists: | pgsql-general pgsql-novice pgsql-sql |
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/
From | Date | Subject | |
---|---|---|---|
Next Message | Raymond O'Donnell | 2010-02-01 12:17:19 | Re: How to test my new install |
Previous Message | Leo Mannhart | 2010-02-01 11:17:19 | Re: combine SQL SELECT statements into one |
From | Date | Subject | |
---|---|---|---|
Next Message | sfarley1 | 2010-02-01 13:23:39 | Question about migrating data. |
Previous Message | Leo Mannhart | 2010-02-01 11:17:19 | Re: combine SQL SELECT statements into one |
From | Date | Subject | |
---|---|---|---|
Next Message | 8q5tmkyqry | 2010-02-01 13:31:38 | selecting rows tagged with "a" but not "b" |
Previous Message | Leo Mannhart | 2010-02-01 11:17:19 | Re: combine SQL SELECT statements into one |