Re: transposing data for a view - Mailing list pgsql-sql

From Josh Berkus
Subject Re: transposing data for a view
Date
Msg-id web-495988@davinci.ethosmedia.com
Whole thread Raw
In response to transposing data for a view  (jeremy@wundt.psychiatry.uiowa.edu (H Jeremy Bockholt))
Responses Re: transposing data for a view  ("Aasmund Midttun Godal" <postgresql@envisity.com>)
List 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
informationtechnology      josh@agliodbs.com  and data management solutions       (415) 565-7293 for law firms, small
businesses       fax 621-2533   and non-profit organizations.      San Francisco
 


pgsql-sql by date:

Previous
From: Roberto Mello
Date:
Subject: Re: Primary key with oid + name : error, which solution ?
Next
From: Stephan Szabo
Date:
Subject: Re: Primary key with oid + name : error, which solution ?