views:

155

answers:

1

(I'm using postgres)

Are there any aggregate functions that work on strings?

I want to write a query along the lines of

select table1.name, join(' - ', unique(table2.horse)) as all_horses
from table1 inner join table2 on table1.id = table2.fk
group by table1.name

Given these 2 tables:

| table1          |               | table2                    |
| id (pk) | name  |               | id (pk) | horse   |  fk   |
+---------+-------+               +---------+---------+-------+ 
|       1 | john  |               |       1 | redrum  |     1 |
|       2 | frank |               |       2 | chaser  |     1 |
                                  |       3 | cigar   |     2 |

The query should return:

| name   |   all_horses      |
+--------+-------------------+
| john   |   redrum - chaser |
| frank  |   cigar           |

Do functions that along the lines of join and unique exist in any DBs for strings?

A: 
select table1.name, 
    array_to_string( array_agg( distinct table2.horse ), ' - ' ) as all_horses
from table1 inner join table2 on table1.id = table2.fk
group by table1.name
Michael Buen
hmm don't seem to have those functions defined - can you help me close the question as it's a duplicate of 43870 ?
EoghanM
try to upgrade to 8.4, array_agg is built-in. regarding closing the question, it needs 5 close, as of now only 1 closed your question. you can delete your own question
Michael Buen