X-Original-To: pgsql-sql@postgresql.org Received: from localhost (postgresql.org [64.49.215.8]) by postgresql.org (Postfix) with ESMTP id 318FE4759AF for ; Fri, 14 Feb 2003 04:48:21 -0500 (EST) Received: from fzkmail2.fzk.de (fzkmail2.fzk.de [141.52.27.52]) by postgresql.org (Postfix) with SMTP id E2DD6475957 for ; Fri, 14 Feb 2003 04:48:19 -0500 (EST) Received: FROM resy5.fzk.de BY fzkmail2.fzk.de ; Fri Feb 14 10:48:18 2003 +0100 Received: œby rodos.fzk.de with ESMTP (8.8.6 (PHNE_17135)/8.7.1) id KAA23508; Fri, 14 Feb 2003 10:48:17 +0100 (MET) Message-ID: <3E4CBB60.F32C76D5@rodos.fzk.de> Date: Fri, 14 Feb 2003 10:48:17 +0100 From: Christoph Haller X-Mailer: Mozilla 4.77 [en] (X11; U; HP-UX B.10.20 9000/780) X-Accept-Language: en MIME-Version: 1.0 To: vc@basebeans.com Cc: pgsql-sql@postgresql.org Subject: Re: Table Pivot Content-Type: text/plain; charset=iso-8859-2 Content-Transfer-Encoding: 7bit X-Virus-Scanned: by AMaViS new-20020517 X-Archive-Number: 200302/326 X-Sequence-Number: 11724 > > How do you do a table Pivot in PostgreSQL? > I'll post you this old mail: > > I saw something that might somewhat a bit more > > flexible solution using SQL. I don't know if it works > > in PostgreSQL. I saw it at the MySQL site. > > > > The following is the URL: > > http://www.mysql.com/articles/wizard/index.html > > > > Has anyone tried this on a PostgreSQL database ? Actually, I'm rather annoyed with the article author. He first claims that Joe Celko reccommends expensive add-on software for crosstabs (Joe does not) and then goes on to use one of Joe's own solutions. However, given the author's thouroughness otherwise, I'm sure the innaccuracy is due to some kind of misunderstanding. There are, in fact, 3 simple SQL-based solutions to the crosstab problem. Which one you use depends on the shape of your data. I am not going to cover them in detail here (I'll save that for an article) but to sum up: 1) The SUM(CASE()) statement method, as outlined in the article, which is good for crosstabs expecting small numbers of columns. Or, in the case of this article, good for RDBMS which do not support subselects. 2) The LEFT JOIN + Sub-Select method, which is good for crosstabs with lots of columns but not that many rows in the crosstabbed table. 3) The "crosstab reference grid" method, which is good for large tables and crosstabs with lots of columns, but requires setup and maintainence by trigger. Joe Celko covers these 3 types in "SQL for Smarties". I will write a PostgreSQL implementation in a later article. -Josh Berkus I have an extended example using the 1) method implemented in plpgsql. Let me know if you want to have a look at it. Regards, Christoph