Egidi
Egidi

Reputation: 1776

Postgresql - Stuck building a plpgsql function

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,

Upvotes: 1

Views: 93

Answers (1)

user330315
user330315

Reputation:

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;

Upvotes: 5

Related Questions