-2

I am a beginner in plpgsql and i am stuck coding a function. I need a function that does the following:

Giving a table, a id_field in that table and another field in that table it does:

ORIGINAL TABLE

id_field     field_traspose
---------    --------------
    1              A
    1              B
    1              C
    2              A
    3              F
    3              X

RESULT

id_field     field_traspose
---------    --------------
    1              A, B, C
    2              A
    3              F, X

My attempt:

CREATE OR REPLACE FUNCTION traspose(mytable character varying, id_field character varying, field_traspose character varying)
  RETURNS setof RECORD AS
$BODY$ 
DECLARE
    r record;
    result record;
BEGIN

FOR r IN EXECUTE 'SELECT '||id_field||','||field_traspose||'  from '||mytable LOOP

-- Here should go the logic that joins every field_traspose for a same id_field and
--returns the record as one of the returning records (can be many different id_fields)   

RETURN NEXT result;
END LOOP;

RETURN;
END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;

I'm stuck at this point. Regards,

2

1 Answer 1

4

No need for such a function, this is already built-in:

select id_field, 
       string_agg(field_traspose, ', ' order by field_traspose) 
from the_table 
group by id_field
order by id_field;
3
  • I am in Postgresql 8.4, are you sure this works in 8.4 or only above 9? I am getting a syntax error
    – Egidi
    Commented Feb 5, 2015 at 12:57
  • I found that array_to_string(array_agg(whatever), ',')) does the same in postgresql 8.4 than string_agg
    – Egidi
    Commented Feb 5, 2015 at 13:04
  • 1
    @Egidi: you didn't mention you were using an unsupported and outdated Postgres version
    – user1822
    Commented Feb 5, 2015 at 13:06

Not the answer you're looking for? Browse other questions tagged or ask your own question.