X-Original-To: pgsql-admin@postgresql.org Received: from joeconway.com (66-146-172-86.skyriver.net [66.146.172.86]) by postgresql.org (Postfix) with ESMTP id 4605247617D for ; Tue, 18 Mar 2003 17:06:58 -0500 (EST) Received: from [206.19.64.3] (account jconway HELO joeconway.com) by joeconway.com (CommuniGate Pro SMTP 4.0.4) with ESMTP-TLS id 1667957; Tue, 18 Mar 2003 14:43:04 -0800 Message-ID: <3E7797F1.2090607@joeconway.com> Date: Tue, 18 Mar 2003 14:04:33 -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: Jodi Kanter Cc: Postgres Admin List Subject: Re: sql question References: <003801c2ed80$7cf65370$de138f80@virginia.edu> In-Reply-To: <003801c2ed80$7cf65370$de138f80@virginia.edu> Content-Type: text/plain; charset=us-ascii; format=flowed Content-Transfer-Encoding: 7bit X-Archive-Number: 200303/301 X-Sequence-Number: 7941 Jodi Kanter wrote: > Can someone tell me how to create a query that will list values in a > field across columns instead of listing them in row form. Can this be > done in one sql query? Thanks Jodi Are you referring to a crosstab, i.e.: select * from cth; id | rowid | rowdt | attribute | val ----+-------+---------------------+----------------+--------------- 1 | test1 | 2003-03-01 00:00:00 | temperature | 42 2 | test1 | 2003-03-01 00:00:00 | test_result | PASS 3 | test1 | 2003-03-01 00:00:00 | volts | 2.6987 4 | test2 | 2003-03-02 00:00:00 | temperature | 53 5 | test2 | 2003-03-02 00:00:00 | test_result | FAIL 6 | test2 | 2003-03-02 00:00:00 | test_startdate | 01 March 2003 7 | test2 | 2003-03-02 00:00:00 | volts | 3.1234 (7 rows) SELECT * FROM crosstab( 'SELECT rowid, attribute, val FROM cth ORDER BY 1', 'SELECT DISTINCT attribute FROM cth ORDER BY 1') AS c(rowid text, temperature int4, test_result text, test_startdate timestamp, volts float8); rowid | temperature | test_result | test_startdate | volts -------+-------------+-------------+---------------------+-------- test1 | 42 | PASS | | 2.6987 test2 | 53 | FAIL | 2003-03-01 00:00:00 | 3.1234 (2 rows) There is an older version of the crosstab function above, in PostgreSQL 7.3.x, in contrib/tablefunc. The one shown above is a significant improvement that should be in 7.4 when it's released, but it will work fine with 7.3.x. If you want a copy of the updated version, you can get it here: http://www.joeconway.com/ There are some pure SQL ways to do this also; search the list archives for the sql and general lists: http://archives.postgresql.org/pgsql-sql/ http://archives.postgresql.org/pgsql-general/ HTH, Joe