Re: PIVOT of data - Mailing list pgsql-sql

From Josh Berkus
Subject Re: PIVOT of data
Date
Msg-id web-25229@davinci.ethosmedia.com
Whole thread Raw
In response to Re: PIVOT of data  (Tim Perdue <tim@perdue.net>)
List 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 totaltvFROM clientsGROUP BY client_address ) AS tv_totalsON
tv_totals.client_address= clients.client_address
 
LEFT OUTER JOIN (SELECT client_address, sum(news_ads) as totalnewsFROM clientsGROUP BY client_address ) AS
news_totalsONnews_totals.client_address = clients.client_address
 
LEFT OUTER JOIN (SELECT client_address, sum(posters) as totalpostersFROM clientsGROUP BY client_address ) AS
poster_totalsONposter_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
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: Tim Perdue
Date:
Subject: Re: PIVOT of data
Next
From: Richard Huxton
Date:
Subject: Re: need to join successive log entries into one