Re: combine SQL SELECT statements into one

Поиск
Список
Период
Сортировка
От Sam Mason
Тема Re: combine SQL SELECT statements into one
Дата
Msg-id 20100201120849.GZ5407@samason.me.uk
обсуждение исходный текст
Ответ на combine SQL SELECT statements into one  (Neil Stlyz <neilstylz@yahoo.com>)
Список pgsql-general
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/

В списке pgsql-general по дате отправления:

Предыдущее
От: Ivano Luberti
Дата:
Сообщение: Unusual table size and very slow inserts
Следующее
От: Raymond O'Donnell
Дата:
Сообщение: Re: How to test my new install