From: Joe Conway <mail@joeconway.com>
To: Jodi Kanter <jkanter@virginia.edu>
Cc: Postgres Admin List <pgsql-admin@postgresql.org>
Subject: Re: sql question
Date: Tue, 18 Mar 2003 14:04:33 -0800
Message-ID: <3E7797F1.2090607@joeconway.com> (raw)
In-Reply-To: <003801c2ed80$7cf65370$de138f80@virginia.edu>
References: <003801c2ed80$7cf65370$de138f80@virginia.edu>
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
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Reply to all the recipients from your mail client; the link fills in
the headers below: reply via email
Some clients, webmail especially, drop In-Reply-To and References from
a link, and the reply then starts a new thread: use the mbox below.
To: pgsql-admin@postgresql.org
Cc: mail@joeconway.com, jkanter@virginia.edu
Subject: Re: sql question
In-Reply-To: <3E7797F1.2090607@joeconway.com>
References: <003801c2ed80$7cf65370$de138f80@virginia.edu> <3E7797F1.2090607@joeconway.com>
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox