Re: dynamic crosstab

From: Joe Conway <mail(at)joeconway(dot)com>
To: Florent THOMAS <mailinglist(at)tdeo(dot)fr>
Cc: postgesql general <pgsql-general(at)postgresql(dot)org>
Subject: Re: dynamic crosstab
Date: 2010-02-01 00:13:06
Message-ID: 4B661C92.4030900@joeconway.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On 01/31/2010 03:52 PM, Florent THOMAS wrote:
> Hello everybody,
>
> I'm trying to find out how to have a dynamic crosstab as in excel,
> ireport,etc...
> As i understand of the manual here :
> http://docs.postgresqlfr.org/8.4/tablefunc.html
> I can have multiple columns.
>
> Unfortunately, it seems indispensible to name the columns in the AS clause.
> Am I right or is ther a way to let the query generate the columns and
> there name without naming them?

Wow, second time this week this has come up. Maybe it ought to be an FAQ.

Anyway, your best bet is to use crosstab from contrib/tablefunc, and
wrap it with application code that dynamically executes the query with
the needed column definitions. It is a simple two step process:

Using crosstab(text source_sql, text category_sql),

- first execute category_sql to get a list of columns
- dynamically build the complete crosstab SQL including the columns
- execute the crosstab SQL

The parser/planner requires the column type information because the
result is potentially filtered (WHERE clause) or joined (FROM CLAUSE)
with other relations. There is no way around this, at least not
currently, and probably not ever in this form. If PostgreSQL ever
supports true procedures (i.e. CALL sp_crosstab(...)), then it would be
possible to forego the column definitions as joining and filtering would
not be possible in that scenario.

Joe

In response to

Browse pgsql-general by date

  From Date Subject
Next Message ray 2010-02-01 01:15:16 How to test my new install
Previous Message Scott Marlowe 2010-01-31 23:55:59 Re: problem with triggers