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,