pg.ddx.io  pgsql-sql@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Florian Weimer <fweimer@bfk.de>
To: pgsql-sql@postgresql.org
Subject: Selecting exactly one row for each column value
Date: Tue, 06 Mar 2007 16:03:36 +0100
Message-ID: <82hcsy4do7.fsf@mid.bfk.de> (raw)

I've got the following table:

fweimer=> 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 = o.a LIMIT 1), 
     (SELECT c FROM TAB i WHERE i.a = 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?

-- 
Florian Weimer                <fweimer@bfk.de>
BFK edv-consulting GmbH       http://www.bfk.de/
Kriegsstraße 100              tel: +49-721-96201-1
D-76133 Karlsruhe             fax: +49-721-96201-99



view thread (5+ messages)  latest in thread

Message-ID: <82hcsy4do7.fsf@mid.bfk.de>
Permalink:  ../82hcsy4do7.fsf@mid.bfk.de/
Also on:    postgresql.org/message-id/82hcsy4do7.fsf@mid.bfk.de

 · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients using the --to and --cc options:
  reply via email

  To: pgsql-sql@postgresql.org
  Cc: fweimer@bfk.de
  Subject: Re: Selecting exactly one row for each column value
  In-Reply-To: <82hcsy4do7.fsf@mid.bfk.de>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox