Re: transposing data for a view

From: "Josh Berkus" <josh(at)agliodbs(dot)com>
To: jeremy(at)wundt(dot)psychiatry(dot)uiowa(dot)edu (H Jeremy Bockholt), pgsql-sql(at)postgresql(dot)org
Subject: Re: transposing data for a view
Date: 2001-10-31 20:42:10
Message-ID: web-495988@davinci.ethosmedia.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

Jeremy,

First, to do a pivot table, you have to be using Postgres 7.1.x. 7.0.x
will not do it. So upgrade now.

> I want to create a flattened out view that looks like the following:
>
> scanid | A_volume | B_volume | C_volume
> ----------------------------------------
> 1 34.4 32.1 29.1
> 2 32.4 33.2 35.6

There are two approaches, the simple approach and the complex. The
simple approach requires you to know in advance of building the view all
of the possible values for your category column. The complex approach,
which is dynamic, requires a rather sophisticated function (which I will
write eventually, really!) so we won't go into it here.

The simple approach is to create each column as a sub-select in the FROM
clause of your statement. So, per the example above:

SELECT scanid, A_volume, B_volume, C_volume
FROM (SELECT scanid FROM volumes GROUP BY scanid) scan
LEFT OUTER JOIN
(SELECT scanid, volume as A_volume FROM volumes WHERE region = 'A') av
ON scan.scanid = av.scanid LEFT OUTER JOIN
(SELECT scanid, volume as B_volume FROM volumes WHERE region = 'B') bv
ON scan.scanid = bv.scanid LEFT OUTER JOIN
(SELECT scanid, volume as C_volume FROM volumes WHERE region = 'C') cv
ON scan.scanid = cv.scanid
ORDER BY scanid;

This approach can be adapted to include aggregates and the like.

-Josh Berkus

______AGLIO DATABASE SOLUTIONS___________________________
Josh Berkus
Complete information technology josh(at)agliodbs(dot)com
and data management solutions (415) 565-7293
for law firms, small businesses fax 621-2533
and non-profit organizations. San Francisco

In response to

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Stephan Szabo 2001-10-31 22:08:55 Re: Primary key with oid + name : error, which solution ?
Previous Message Roberto Mello 2001-10-31 20:15:18 Re: Primary key with oid + name : error, which solution ?