Re: sum of string columns, why ?

From: "Ross J(dot) Reedstrom" <reedstrm(at)rice(dot)edu>
To: pgsql-sql(at)postgresql(dot)org
Subject: Re: sum of string columns, why ?
Date: 2001-06-18 16:41:37
Message-ID: 20010618114137.J14955@rice.edu
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

On Wed, Jun 06, 2001 at 06:13:18PM -0300, Marcos Vaz - ( NewAge Group ) wrote:
> I have one table with thwo columns, user and text, why sum all the text
> fields of the one user ?

I assume you mean 'how' not 'why'?

You don't give a lot of detail, like what you mean by 'sum all the text'. One
interpretation is 'count the number of text entries for one user', as so:

select user, count(text) from some_table group by user;

If instead you mean concatenate all the text and return it as one big string,
that's a bit trickier. You need a custom aggregate function that concatenates
strings. Here's one I use to generate comma delimited concatenations:

REATE AGGREGATE catenate ( BASETYPE = text, SFUNC = commacat, STYPE = text, INITCOND =
'' );

CREATE FUNCTION "commacat" (text,text) RETURNS text AS '
begin
if $1 <> '''' then
return $1 || '', '' || $2 ;
else
return $2;
end if;
end;
' LANGUAGE 'plpgsql';

It works as so:

select user,catenate(text) from some_table group by user;

You'll want to change the helper function to not inserting commas, however.

Ross

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Josh Berkus 2001-06-18 16:51:08 Re: Better Archives?
Previous Message Roberto Mello 2001-06-18 16:37:06 Re: Better Archives?