From: | Joe Conway <mail(at)joeconway(dot)com> |
---|---|
To: | James Taylor <jtx(at)hatesville(dot)com> |
Cc: | pgsql-sql(at)postgresql(dot)org |
Subject: | Re: Rows as Columns |
Date: | 2003-04-02 06:26:10 |
Message-ID: | 3E8A8282.2020603@joeconway.com |
Views: | Raw Message | Whole Thread | Download mbox | Resend email |
Thread: | |
Lists: | pgsql-sql |
James Taylor wrote:
> This would return something like:
>
> name | data
> ------------------------
> first_name | Sam
> last_name | Smith
> phone_number | 555-1212
>
>
> Well, I need it to somehow return that data in this format:
>
> first_name | last_name | phone_number
> ----------------------------------------
> Sam | Smith | 555-1212
>
> The information in Types is not static, so I can't declare the col names
> based on what you see here.
>
If you know at query writing time, which attributes (distinct values of
name from the types table) you want, then you could use the crosstab
function from contrib/tablefunc (except you'll need a newer version --
see url below):
regression=# select d.cust_id, t.name, d.data from types t, data d where
d.t_key = t.id;
cust_id | name | data
---------+--------------+----------
1 | first_name | Sam
2 | first_name | John
1 | last_name | Smith
1 | phone_number | 555-1212
(4 rows)
regression=# select * from crosstab('select d.cust_id, t.name, d.data
from types t, data d where d.t_key = t.id order by 1','select distinct
name from types') as (cust_id int, fn text, ln text, pn text);
cust_id | fn | ln | pn
---------+------+-------+----------
1 | Sam | Smith | 555-1212
2 | John | |
(2 rows)
The version of crosstab() distributed with Postgres 7.3.x cannot do
exactly this, but you can get the latest (same as what is in cvs for
7.4) here:
You want "contrib/tablefunc with hashed crosstab"
HTH,
Joe
From | Date | Subject | |
---|---|---|---|
Next Message | Mike Papper | 2003-04-02 08:09:33 | Finding if a temp table exists in the current connection |
Previous Message | Tom Lane | 2003-04-02 06:03:03 | Re: pesky plpgsql |