Re: generic crosstab ?

From: "David Johnston" <polobo(at)yahoo(dot)com>
To: "'Andreas'" <maps(dot)on(at)gmx(dot)net>, "'Samuel Gendler'" <sgendler(at)ideasculptor(dot)com>
Cc: <pgsql-sql(at)postgresql(dot)org>
Subject: Re: generic crosstab ?
Date: 2012-04-24 21:42:49
Message-ID: 04d701cd2263$323e1ad0$96ba5070$@yahoo.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

From: pgsql-sql-owner(at)postgresql(dot)org [mailto:pgsql-sql-owner(at)postgresql(dot)org]
On Behalf Of Andreas
Sent: Tuesday, April 24, 2012 5:35 PM
To: Samuel Gendler
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: [SQL] generic crosstab ?

Am 24.04.2012 22:08, schrieb Samuel Gendler:

On Tue, Apr 24, 2012 at 1:01 PM, Andreas <maps(dot)on(at)gmx(dot)net> wrote:

Hi,

is there a generic solution to dump the result of a query as a crosstab,
when I can't know how many columns I will need?

E.g. I get something like this:

id, x
1, a
1, b
1, c
2, l
2, m

Yes. You can provide a query which returns the columns to the version of
the crosstab function which looks like this:

crosstab(text source_sql, text category_sql)

It does exactly what you are looking for. The second query returns the set
of values that act as columns in the final result (the pivot for each row in
the result returned by the first query). This allows the function to
correctly insert a null for any column for which there is no row in the
first query results.

I got stuck with an error that translates to "Materialisation mode is needed
but is not allowed in this context."
I couldn't figure out what this materialisation mode is, yet.

Could you please have a look at my query sample?
Both queries work for themselves but crosstab() fails. :(
I checked and there are never more than 20 child_ids per parent_id so there
should be enough columns.

select
crosstab (
$$
select
parent_id as row_name,
'x' || row_number() over ( partition by parent_id order by child_id
) as category,
child_id as value
from
children
order by 1
$$,
$$
select 'x' || generate_series(1, 20) as cat order by 1
$$
);

You must specify the output record structure:

SELECT crosstab(text, text) AS ( col1_name col1_type [, colN_name
colN_type]* )

See: http://www.postgresql.org/docs/9.0/interactive/tablefunc.html for
official usage and examples

Whether this relates to the "materialization node" message you are receiving
I have no idea.

Dave

In response to

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Joe Conway 2012-04-24 22:04:21 Re: generic crosstab ?
Previous Message Andreas 2012-04-24 21:34:55 Re: generic crosstab ?