1

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,

1

1 Answer 1

5

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;
2
  • 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
    Feb 5, 2015 at 12:58
  • 5
    8.4 is EOL, you need an upgrade. Using array_agg() and array_to_string() can get the same result as string_agg(), it just takes some extra work. As of version 9.0 you can use string_agg() by default, but you could create this function yourself in 8.4 Feb 5, 2015 at 13:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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