X-Original-To: pgsql-sql-postgresql.org@postgresql.org Received: from localhost (mx1.hub.org [200.46.208.251]) by postgresql.org (Postfix) with ESMTP id B66A49FB338 for ; Wed, 20 Sep 2006 08:33:41 -0300 (ADT) Received: from postgresql.org ([200.46.204.71]) by localhost (mx1.hub.org [200.46.208.251]) (amavisd-new, port 10024) with ESMTP id 51297-10 for ; Wed, 20 Sep 2006 08:33:31 -0300 (ADT) X-Greylist: domain auto-whitelisted by SQLgrey- Received: from ciao.gmane.org (main.gmane.org [80.91.229.2]) by postgresql.org (Postfix) with ESMTP id 6E9799FB319 for ; Wed, 20 Sep 2006 08:33:29 -0300 (ADT) Received: from list by ciao.gmane.org with local (Exim 4.43) id 1GQ0KG-0002nU-Pl for pgsql-sql@postgresql.org; Wed, 20 Sep 2006 13:33:12 +0200 Received: from srv.protecting.net ([212.126.218.242]) by main.gmane.org with esmtp (Gmexim 0.1 (Debian)) id 1AlnuQ-0007hv-00 for ; Wed, 20 Sep 2006 13:33:12 +0200 Received: from hf0731x by srv.protecting.net with local (Gmexim 0.1 (Debian)) id 1AlnuQ-0007hv-00 for ; Wed, 20 Sep 2006 13:33:12 +0200 X-Injected-Via-Gmane: http://gmane.org/ To: pgsql-sql@postgresql.org From: Harald Fuchs Subject: Re: Need a SQL to create sets of hobbies Date: 20 Sep 2006 13:33:01 +0200 Organization: Linux Private Site Lines: 66 Message-ID: References: <1158729519.6421.271361727@webmail.messagingengine.com> Mime-Version: 1.0 Content-Type: text/plain; charset=US-ASCII X-Complaints-To: usenet@sea.gmane.org X-Gmane-NNTP-Posting-Host: srv.protecting.net X-Archive: encrypt User-Agent: Gnus/5.0808 (Gnus v5.8.8) Emacs/20.7 X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=0.477 tagged_above=0 required=5 tests=AWL, SPF_HELO_PASS, SPF_PASS X-Spam-Level: X-Archive-Number: 200609/138 X-Sequence-Number: 26349 In article <1158729519.6421.271361727@webmail.messagingengine.com>, "CN" writes: > select * from x1; > name | hobby > -------+---------- > John | music > John | arts > Bob | arts > Bob | music > Rocky | computer > Steve | arts > Steve | football > Tom | computer > Tom | music > (9 rows) > Now we have 4 sets of hobbies: > set 1: music, arts > set 2: computer > set 3: arts, football > set 4: computer, music > I am looking for an SQL that creates sets of hobbies in table x2 by > selecting from table x1: > CREATE TABLE x2 (sid INTEGER, hobby TEXT, PRIMARY KEY(sid,hobby)); > and makes x2 contain rows: > sid | hobby > -------+---------- > 1 | music > 1 | arts > 2 | computer > 3 | arts > 3 | football > 4 | computer > 4 | music > where gid starts from 1. You could use something like that: CREATE TEMP TABLE tmp ( id SERIAL NOT NULL, name TEXT NOT NULL, PRIMARY KEY (id) ); INSERT INTO tmp (name) SELECT DISTINCT ON (ARRAY ( SELECT y1.hobby FROM x1 y1 WHERE y1.name = y2.name ORDER BY y1.name, y1.hobby )) y2.name FROM x1 y2; INSERT INTO x2 (sid, hobby) SELECT tmp.id, x1.hobby FROM tmp JOIN x1 ON x1.name = tmp.name;