Re: List Concatination - Mailing list pgsql-sql

From Richard Huxton
Subject Re: List Concatination
Date
Msg-id 3AA8BB73.5647B248@archonet.com
Whole thread Raw
In response to List Concatination  (Josh Berkus <josh@agliodbs.com>)
Responses Re: List Concatination
List pgsql-sql
Josh Berkus wrote:
>         I have an interesting problem.  For purpose of presentation to users,
> I'd like to concatinate a list of VARCHAR values from a subtable.  To
> simplify my actual situation:
> 
> What I'd like to be able to do is present a list of clients and their
> comma-seperated contacts in paragraph form, hence:
> 
> Client                  Contacts
> McMurphy Assoc.         Jim Henson, Pat O'Gannet, Kelley Moore
> 
> Ross Construction       Sara Vaugn, Bill Murray, Peter Frump,
>                         Siskel Ebert
> 
Well, basically you can use a standard join, order it and eliminate
duplicate client names in the application. That's the "proper" way.

But - if you don't care about the order of contacts you can define an
aggregate function:

create aggregate catenate(sfunc1=textcat, basetype=text, stype1=text, initcond1='');

Then group by client and catenate(firstname || ' ' || lastname)

You'll want to read the CREATE AGGREGATE page in the reference manual,
replace textcat with your own routine that adds a comma and you'll need
a finalisation routine to strip the final trailing comma.

Note that this is probably not a good idea - the ordering of the
contacts will not be well-defined. When I asked about this Tom Lane was
quite surprised that it worked, so no guarantees about long-term suitability.

- Richard Huxton


pgsql-sql by date:

Previous
From: Josh Berkus
Date:
Subject: List Concatination
Next
From: Johan Van den Brande
Date:
Subject: Re: perl dbd