Received: from davinci.ethosmedia.com (davinci.ethosmedia.com [209.10.40.250]) by mail.postgresql.org (8.11.1/8.11.1) with ESMTP id f2F54Ux34802 for ; Thu, 15 Mar 2001 00:04:30 -0500 (EST) (envelope-from josh@agliodbs.com) Received: from [209.10.40.250] (account ) by davinci.ethosmedia.com (CommuniGate Pro WebUser 3.4.1) with HTTP id 25229 for ; Wed, 14 Mar 2001 21:04:29 -0800 From: "Josh Berkus" Subject: Re: PIVOT of data To: pgsql-sql@postgresql.org X-Mailer: CommuniGate Pro Web Mailer v.3.4.1 Date: Wed, 14 Mar 2001 21:04:29 -0800 Message-ID: In-Reply-To: <20010314212627.H12986@mail.perdue.net> MIME-Version: 1.0 Content-Type: text/plain; charset="ISO-8859-1" Content-Transfer-Encoding: 8bit X-Archive-Number: 200103/302 X-Sequence-Number: 1966 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@agliodbs.com and data management solutions (415) 565-7293 for law firms, small businesses fax 621-2533 and non-profit organizations. San Francisco