Aggregate Function with Argument

From: David Siegal <dsiegal(at)thecsl(dot)org>
To: pgsql-sql(at)postgresql(dot)org
Subject: Aggregate Function with Argument
Date: 2004-10-18 15:24:33
Message-ID: Pine.LNX.4.58.0410181117500.29842@brave.cs.uml.edu
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

I would like to create an aggregate function that returns a concatenation
of grouped values. It would be particularly useful if I could pass an
optional delimiter into the aggregate function.

For example:

With a table, 'team'...

team_number member_name
--------------------------
1 David
1 Sanjay
1 Marie
2 Josh
2 Rani
...

...a query like:

SELECT team_number, aggregated_concat(member_name, ', ' ) AS members FROM
team GROUP BY team_number;

...would return:

team_number members
-----------------------------------
1 David, Sanjay, Marie
2 Josh, Rani
...

Here's what I've got so far:

/* For the default case, with no delimiter provided: */
CREATE FUNCTION concat(text, text) RETURNS text
AS 'select $1 || $2;'
LANGUAGE SQL
STABLE
RETURNS NULL ON NULL INPUT;

/* With a delimiter provided: */
CREATE FUNCTION concat(text, text, text) RETURNS text
AS 'select $1 || $3 || $2;'
LANGUAGE SQL
STABLE
RETURNS NULL ON NULL INPUT;

CREATE AGGREGATE aggregated_concat (
sfunc = concat,
basetype = text,
stype = text
);

My problem is I don't see how to make aggregated_concat accept an
optional delimiter argument.
Maybe it's not possible?

Any ideas?
Is there some completely different approach I should consider for
concatenating grouped values?

Thanks!
David

David Siegal
Community Software Lab

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Kent Anderson 2004-10-18 15:59:09 Ordering a record returned from a stored procedure
Previous Message Guillaume 2004-10-18 15:18:29 bibliographic schema