From: | "Josh Berkus" <josh(at)agliodbs(dot)com> |
---|---|
To: | pgsql-sql(at)postgresql(dot)org |
Subject: | Re: PIVOT of data |
Date: | 2001-03-15 05:04:29 |
Message-ID: | web-25229@davinci.ethosmedia.com |
Views: | Raw Message | Whole Thread | Download mbox | Resend email |
Thread: | |
Lists: | pgsql-sql |
Srikanth,
Aside from seconding Tim (your database is *not* normalized), the PIVOT
function is only available one of 2 ways:
SQL-ONLY, FIXED COLUMN: If you know your categories in advance, you can
write a complex view using outer joins, sub-selects, and aggregates.
Imagine that we know your types of marketing to be limited to TV, NEWS
and POSTER:
SELECT client_address, tv_totals.totaltv, news_totals.totalnews,
poster_totals.totalposter
FROM clients
LEFT OUTER JOIN (
SELECT client_address, sum(tv_spots) as totaltv
FROM clients
GROUP BY client_address ) AS tv_totals
ON tv_totals.client_address = clients.client_address
LEFT OUTER JOIN (
SELECT client_address, sum(news_ads) as totalnews
FROM clients
GROUP BY client_address ) AS news_totals
ON news_totals.client_address = clients.client_address
LEFT OUTER JOIN (
SELECT client_address, sum(posters) as totalposters
FROM clients
GROUP BY client_address ) AS poster_totals
ON poster_totals.client_address = clients.client_address;
DYNAMIC METHOD: This requires an external programming language, and I'm
not going to write it for you! However, pick you favorite procedural
language (tcl, perl, or C) and write the following:
1. Do an select distinct to obtain each value in the column you want to
use in the headers. Load this series into an array.
2. Dynamically generate query text, adding a column and a LEFT OUTER
JOIN as above into the query for each value in your array.
This method is a lot of work for both you and the server. Why do you
think that MS Access often crashes on a large "crosstab" query?
-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
From | Date | Subject | |
---|---|---|---|
Next Message | Jeff Putsch | 2001-03-15 06:47:29 | Help with UPDATE syntax |
Previous Message | Tim Perdue | 2001-03-15 03:26:27 | Re: PIVOT of data |