0

I got this function to concat fields in my pgSQL-server:

BEGIN
    IF acc IS NULL OR acc = '' THEN
      RETURN instr;
    ELSE
      RETURN acc || ';' || instr;
    END IF;
  END;

It works great, but now I want this function to distinct equal entries. How can I do this?

1
  • Please supply more information. In particular, what is acc? What is instr? Are these parameters? Are they the only fields/variables of interest? Commented Apr 15, 2009 at 12:13

1 Answer 1

2
CREATE TYPE tp_concat AS (data TEXT[], delimiter TEXT);

CREATE OR REPLACE FUNCTION group_concat_iterate(_state tp_concat, _value TEXT, delimiter TEXT, is_distinct boolean)
  RETURNS tp_concat AS
$BODY$
  SELECT
    CASE
      WHEN $1 IS NULL THEN ARRAY[$2]
      WHEN $4 AND $1.data @> ARRAY[$2] THEN $1.data
      ELSE $1.data || $2
  END,
  $3
$BODY$
  LANGUAGE 'sql' VOLATILE;

CREATE OR REPLACE FUNCTION group_concat_finish(_state tp_concat)
  RETURNS text AS
$BODY$
    SELECT array_to_string($1.data, $1.delimiter)
$BODY$
  LANGUAGE 'sql' VOLATILE;

CREATE AGGREGATE group_concat(text, text, boolean) (SFUNC = group_concat_iterate, STYPE = tp_concat, FINALFUNC = group_concat_finish);

Use it like this:

SELECT  GROUP_CONCAT(textfield, ';', TRUE)
FROM    mytable

if you don't want duplicates, and

SELECT  GROUP_CONCAT(textfield, ';', FALSE)
FROM    mytable

if you do.

Sign up to request clarification or add additional context in comments.

2 Comments

@Mike: also see the note about DISTINCT with multiple arguments.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.