X-Original-To: pgsql-sql@postgresql.org Received: from spampd.localdomain (postgresql.org [64.49.215.8]) by postgresql.org (Postfix) with ESMTP id 8CA9C475AF8 for ; Wed, 2 Apr 2003 01:25:51 -0500 (EST) Received: from joeconway.com (66-146-172-86.skyriver.net [66.146.172.86]) by postgresql.org (Postfix) with ESMTP id D047047592C for ; Wed, 2 Apr 2003 01:25:50 -0500 (EST) Received: from [192.168.5.3] (account jconway HELO joeconway.com) by joeconway.com (CommuniGate Pro SMTP 4.0.4) with ESMTP-TLS id 1692585; Tue, 01 Apr 2003 23:01:14 -0800 Message-ID: <3E8A8282.2020603@joeconway.com> Date: Tue, 01 Apr 2003 22:26:10 -0800 From: Joe Conway User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.2.1) Gecko/20021130 X-Accept-Language: en-us, en MIME-Version: 1.0 To: James Taylor Cc: pgsql-sql@postgresql.org Subject: Re: Rows as Columns References: <002801c2f8ad$4888c9f0$4500a8c0@theplague> In-Reply-To: <002801c2f8ad$4888c9f0$4500a8c0@theplague> Content-Type: text/plain; charset=us-ascii; format=flowed Content-Transfer-Encoding: 7bit X-Spam-Status: No, hits=-38.8 required=5.0 tests=BAYES_01,EMAIL_ATTRIBUTION,IN_REP_TO,QUOTED_EMAIL_TEXT, REFERENCES,REPLY_WITH_QUOTES,USER_AGENT_MOZILLA_UA autolearn=ham version=2.50 X-Spam-Level: X-Spam-Checker-Version: SpamAssassin 2.50 (1.173-2003-02-20-exp) X-Archive-Number: 200304/20 X-Sequence-Number: 12721 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: http://www.joeconway.com/ You want "contrib/tablefunc with hashed crosstab" HTH, Joe