From: Michael Fuhr <mike@fuhr.org>
To: Volkan YAZICI <volkan.yazici@gmail.com>
Cc: pgsql-sql@postgresql.org
Subject: Re: Combining two SELECTs by same filters
Date: Wed, 26 Oct 2005 10:15:58 -0600
Message-ID: <20051026161558.GA44965@winnie.fuhr.org> (raw)
In-Reply-To: <7104a7370510260816l9262d19j808d23c023e8445e@mail.gmail.com>
References: <7104a7370510260816l9262d19j808d23c023e8445e@mail.gmail.com>
On Wed, Oct 26, 2005 at 06:16:13PM +0300, 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.
If you can accept multiple rows instead of multiple columns then
one way would be to group by the hour:
SELECT date_trunc('hour', dt) AS hour, count(*)
FROM sales
WHERE id = 2
AND date_trunc('hour', dt) IN ('2005-10-25 21:00:00', '2005-10-25 22:00:00')
GROUP BY hour
ORDER BY hour;
hour | count
---------------------+-------
2005-10-25 21:00:00 | 6
2005-10-25 22:00:00 | 2
(2 rows)
Here's another possibility, but I find it a bit ugly:
SELECT sum(CASE date_trunc('hour', dt)
WHEN '2005-10-25 21:00:00' THEN 1
ELSE 0
END) AS count1,
sum(CASE date_trunc('hour', dt)
WHEN '2005-10-25 22:00:00' THEN 1
ELSE 0
END) AS count2
FROM sales
WHERE id = 2;
count1 | count2
--------+--------
6 | 2
(1 row)
If you're looking for the fastest method then use EXPLAIN ANALYZE
on each to see what works best on your data set.
--
Michael Fuhr
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: mike@fuhr.org, volkan.yazici@gmail.com
Subject: Re: Combining two SELECTs by same filters
In-Reply-To: <20051026161558.GA44965@winnie.fuhr.org>
* 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