From: Josh Berkus <josh@agliodbs.com>
To: Jeff Eckermann <jeff_eckermann@yahoo.com>
To: Aasmund Midttun Godal <postgresql@envisity.com>
To: josh@agliodbs.com
Cc: jeremy@wundt.psychiatry.uiowa.edu
Cc: pgsql-sql@postgresql.org
Subject: Re: transposing data for a view
Date: Thu, 01 Nov 2001 08:17:00 -0800
Message-ID: <web-496664@davinci.ethosmedia.com> (raw)
In-Reply-To: <20011101154744.98632.qmail@web20802.mail.yahoo.com>
Jeff,
> SELECT
> scanid,
> sum ( CASE WHEN region = 'A' THEN volume ELSE NULL
> )
> AS A_volume,
> sum ( CASE WHEN region = 'B' THEN volume ELSE NULL
> )
> AS B_volume,
> sum ( CASE WHEN region = 'C' THEN volume ELSE NULL
> )
> AS C_volume
> FROM table
> GROUP BY scanid;
Hey, that's an elegant solution to doing it in 7.0.3. I hadn't thought
of it. Jeremy, never mind what I said about being forced to upgrade.
Upgrading *would* still be a good idea, of course.
Of couse, it's only *half* a solution. Your query will result in:
scanid A_volume B_volume C_volume
1 34.5
1 55.1
1 12.3
2 11.1
etc.
For the second half of the solution, Jeremy needs to create the above as
a view ('volume_rollup_1') and apply this second view:
SELECT scanid, SUM(A_volume) as A_volume, SUM(B_Volume) as B_Volume,
SUM(C_volume) as C_volume
FROM volume_rollup_1;
This will give Jeremy the "pivot" grid he's looking for.
> BTW, I don't believe the self-join approach proposed
> earlier will work, because joining on "scanid" will
> create a cartesian type join where the region values
> will be duplicated (multiplicated!).
Not if you're talking about my query, they won't. I use that query form
in many projects to create roll-ups; it's the "best" SQL92 approach to
the "pivot table" problem. However, it will not work in 7.0.3.
-Josh
______AGLIO DATABASE SOLUTIONS___________________________
Josh Berkus
Complete information technology josh@agliodbs.com
and data management solutions (415) 565-7293
for law firms, small businesses fax 621-2533
and non-profit organizations. San Francisco
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 using the --to and --cc options:
reply via email
To: pgsql-sql@postgresql.org
Cc: josh@agliodbs.com, jeff_eckermann@yahoo.com, postgresql@envisity.com, jeremy@wundt.psychiatry.uiowa.edu
Subject: Re: transposing data for a view
In-Reply-To: <web-496664@davinci.ethosmedia.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