Re: Combining two SELECTs by same filters

From: Scott Marlowe <smarlowe(at)g2switchworks(dot)com>
To: Volkan YAZICI <volkan(dot)yazici(at)gmail(dot)com>
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: Combining two SELECTs by same filters
Date: 2005-10-26 15:59:05
Message-ID: 1130342345.2872.18.camel@state.g2switchworks.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

On Wed, 2005-10-26 at 10:16, Volkan YAZICI wrote:

> => SELECT
> -> (SELECT count(id) FROM sales
> -> WHERE id = 2
> -> AND date_trunc('hour', dt) = '2005-10-25 21:00:00'),
> -> (SELECT count(id) FROM sales
> -> WHERE id = 2
> -> AND date_trunc('hour', dt) = '2005-10-25 22:00:00');
> ?column? | ?column?
> ----------+----------
> 6 | 2
> (1 row)
>
> Isn't it possible to combine these two SELECTs as one. Because one of
> their filters are same: id = 2. I'm just trying to avoid making 2
> scans with nearly same filters.

Do something like this:

select count(id)
from sales
where id=2 and
dt between 'firstdatehere' and 'lastdatehere'
group by date_trunc('hour', dt);

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Jan Wieck 2005-10-26 16:09:05 Re: why vacuum
Previous Message Gary Stainburn 2005-10-26 15:38:48 Re: select best price