pg.ddx.io  pgsql-sql@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: 李彦 Ian Li <liyan82@gmail.com>
To: Stefano Dal Pra <s.dalpra@gmail.com>
Cc: PostgreSQL Performance <pgsql-performance@postgresql.org>
Subject: Re: two queryes in a single tablescan
Date: Thu, 18 Oct 2007 10:24:50 +0800
Message-ID: <4716C3F2.5040206@gmail.com> (raw)
In-Reply-To: <290a5abc0710170530v215cb2b0q4fa000ad43096a28@mail.gmail.com>
References: <290a5abc0710170530v215cb2b0q4fa000ad43096a28@mail.gmail.com>

I remember when I was using SQL server we did like like that:

SELECT count(CASE WHEN A THEN 1 END) AS cnt_a, count(CASE WHEN B 
THEN 1 END) AS cnt_b FROM tab WHERE C;

I did a little test with pg_bench data, also works in PostgreSQL:

test=# select count(*) from history where tid = 1;
  count
-------
    574
(1 行)

时间: 9.553 ms
test=# select count(*) from history where tid = 2;
  count
-------
   1107
(1 行)

时间: 8.949 ms
test=# select count(CASE WHEN tid = 1 then 1 END) as t1_cont, 
count(case when tid=2 then 1 end) as t2_cnt from history ;
  t1_cont | t2_cnt
---------+--------
      574 |   1107
(1 行)

时间: 17.182 ms

Hope that helps.

Regards

Stefano Dal Pra wrote:
> Hi everybody,
> 
> suppose you have a large table tab and two (or more) queryes like this:
> 
> SELECT count(*),A FROM tab WHERE C GROUP BY A;
> SELECT count(*),B FROM tab WHERE C GROUP BY B;
> 
> is there any way to get both results in a single query,
> eventually through stored procedure?
> The retrieved [count(*),A] ; [count(*),B)] data couldnt fit
> on a single table, of course.
> 
> The main goal would be to get multiple results while scanning the
> table[s] once only
> thus getting results in a faster  way.
> 
> This seems to me quite a common situation but i have no clue whether a neat
> solution can be implemented through stored procedure.
> 
> Any hint?
> 
> Thank you
> 
> Stefano




view thread (9+ messages)  latest in thread

Message-ID: <4716C3F2.5040206@gmail.com>
Permalink:  ../4716C3F2.5040206@gmail.com/
Also on:    postgresql.org/message-id/4716C3F2.5040206@gmail.com

 · 

reply

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: liyan82@gmail.com, s.dalpra@gmail.com, pgsql-performance@postgresql.org
  Subject: Re: two queryes in a single tablescan
  In-Reply-To: <4716C3F2.5040206@gmail.com>

* 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