From: | Florian Weimer <fweimer(at)bfk(dot)de> |
---|---|
To: | pgsql-sql(at)postgresql(dot)org |
Subject: | Selecting exactly one row for each column value |
Date: | 2007-03-06 15:03:36 |
Message-ID: | 82hcsy4do7.fsf@mid.bfk.de |
Views: | Raw Message | Whole Thread | Download mbox | Resend email |
Thread: | |
Lists: | pgsql-sql |
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(at)bfk(dot)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
From | Date | Subject | |
---|---|---|---|
Next Message | A. Kretschmer | 2007-03-06 15:17:19 | Re: Selecting exactly one row for each column value |
Previous Message | Shavonne Marietta Wijesinghe | 2007-03-06 14:49:17 | Re: convert to a string |