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/

-- 
Sent via pgsql-general mailing list (pgsql-general@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-general

Reply via email to