Received: from localhost (maia-5.hub.org [200.46.204.182]) by postgresql.org (Postfix) with ESMTP id 9716F9FBAE0 for ; Tue, 6 Mar 2007 11:06:02 -0400 (AST) Received: from postgresql.org ([200.46.204.71]) by localhost (mx1.hub.org [200.46.204.182]) (amavisd-new, port 10024) with ESMTP id 13687-05 for ; Tue, 6 Mar 2007 11:05:31 -0400 (AST) X-Greylist: from auto-whitelisted by SQLgrey-1.7.4 Received: from mx01.bfk.de (mx01.bfk.de [193.227.124.2]) by postgresql.org (Postfix) with ESMTP id 1EC809FBB35 for ; Tue, 6 Mar 2007 11:03:42 -0400 (AST) Received: from mx00.int.bfk.de ([10.119.110.2]) by mx01.bfk.de with esmtps (TLS-1.0:RSA_AES_256_CBC_SHA1:32) id 1HObCW-0006hy-Ci for pgsql-sql@postgresql.org; Tue, 06 Mar 2007 16:03:40 +0100 Received: from fweimer by bfk.de with local id 1HObCS-0003K4-9C for pgsql-sql@postgresql.org; Tue, 06 Mar 2007 16:03:36 +0100 To: pgsql-sql@postgresql.org Subject: Selecting exactly one row for each column value From: Florian Weimer Date: Tue, 06 Mar 2007 16:03:36 +0100 Message-ID: <82hcsy4do7.fsf@mid.bfk.de> MIME-Version: 1.0 Content-Type: text/plain; charset=iso-8859-1 Content-Transfer-Encoding: quoted-printable X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=0.052 tagged_above=0 required=5 tests=AWL, BAYES_50 X-Spam-Level: X-Archive-Number: 200703/42 X-Sequence-Number: 27680 I've got the following table: fweimer=3D> SELECT * FROM tab; a | b | c ---+---+--- 1 | 2 | 3 5 | 6 | 7 1 | 2 | 2 2 | 3 | 4 1 | 2 | 2 2 | 3 | 4 For each value in the first column, I need one (and only one) matching row from the table. A possible solution is: a | b | c ---+---+--- 5 | 6 | 7 2 | 3 | 4 1 | 2 | 3 Of course, SELECT a, (SELECT b FROM tab i WHERE i.a =3D o.a LIMIT 1),=20 (SELECT c FROM TAB i WHERE i.a =3D o.a LIMIT 1) FROM tab o GROUP BY o.= a; does the trick, but this approach seems to rely on undefined behavior and quickly gets messy when the number of columns increases. Is there a better way to implement this? --=20 Florian Weimer BFK edv-consulting GmbH http://www.bfk.de/ Kriegsstra=DFe 100 tel: +49-721-96201-1 D-76133 Karlsruhe fax: +49-721-96201-99