Re: Still don't know how to build this string ?

From: "Richard Huxton" <dev(at)archonet(dot)com>
To: <pgsql-sql(at)postgresql(dot)org>, <juerg(dot)rietmann(at)pup(dot)ch>
Subject: Re: Still don't know how to build this string ?
Date: 2001-03-26 12:23:15
Message-ID: 006501c0b5ef$897f33c0$1001a8c0@archonet.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

From: <juerg(dot)rietmann(at)pup(dot)ch>

> I have a table with diameters and types. I need to build a comma separated
> string.
>
> typ diam
> 01 800
[snip]
>
> select diam from zylinder where typ='01'
>
> should produce the string "800,840,870,1120"

Try the following as a starting point:

CREATE FUNCTION comma_join(text,text) RETURNS text AS '
BEGIN
IF $1>\'\' AND $2>\'\' THEN
RETURN $1 || \',\' || $2;
ELSE
RETURN $1 || $2;
END IF;
END;
' LANGUAGE 'plpgsql';

CREATE AGGREGATE joinall (
sfunc = comma_join,
basetype = text,
stype = text,
initcond = ''
);

\d dia
Table "dia"
Attribute | Type | Modifier
-----------+---------+----------
typ | integer |
diam | integer |

SELECT typ,joinall(diam::text) FROM dia GROUP BY typ;
typ | joinall
-----+----------------------------
1 | 800,840,870,1120
2 | 760,800,900,1200,1234,1352
(2 rows)

Note the explicit cast of diam into text.

- Richard Huxton

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Cedar Cox 2001-03-26 13:44:56 Re: Functions and Triggers
Previous Message Richard Huxton 2001-03-26 12:04:41 Re: Functions and Triggers