I implemented this function in my Postgres database: http://www.cureffi.org/2013/03/19/automatically-creating-pivot-table-column-names-in-postgresql/
Here's the function:
create or replace function xtab (tablename varchar, rowc varchar, colc varchar, cellc varchar, celldatatype varchar) returns varchar language plpgsql as $$ declare dynsql1 varchar; dynsql2 varchar; columnlist varchar; begin -- 1. retrieve list of column names. dynsql1 = 'select string_agg(distinct '||colc||'||'' '||celldatatype||''','','' order by '||colc||'||'' '||celldatatype||''') from '||tablename||';'; execute dynsql1 into columnlist; -- 2. set up the crosstab query dynsql2 = 'select * from crosstab ( ''select '||rowc||','||colc||','||cellc||' from '||tablename||' group by 1,2 order by 1,2'', ''select distinct '||colc||' from '||tablename||' order by 1'' ) as ct ( '||rowc||' varchar,'||columnlist||' );'; return dynsql2; end $$;
So now I can call the function:
select xtab('globalpayments','month','currency','(sum(total_fees)/sum(txn_amount)*100)::decimal(48,2)','text');
Which returns (since the return type of the function is varchar):
select * from crosstab ( 'select month,currency,(sum(total_fees)/sum(txn_amount)*100)::decimal(48,2) from globalpayments group by 1,2 order by 1,2' , 'select distinct currency from globalpayments order by 1' ) as ct ( month varchar,CAD text,EUR text,GBP text,USD text );
How can I make this function not only generate dynamic crosstab code, but also execute the result? I., the result is when I manually copy / paste / execute this. But I want it to be executed without this extra step: the function must collect a dynamic request and execute it:

Change 1
This function is approaching, but I need it to return more than just the first column of the first record
Taken from: Is there a way to execute a query inside a string value (e.g. eval) in PostgreSQL?
create or replace function eval( sql text ) returns text as $$ declare as_txt text; begin if sql is null then return null ; end if ; execute sql into as_txt ; return as_txt ; end; $$ language plpgsql
usage: select * from eval($$select * from analytics limit 1$$)
However, it simply returns the first column of the first record:
eval ---- 2015
when the actual result is as follows:
Year, Month, Date, TPV_USD ---- ----- ------ -------- 2016, 3, 2016-03-31, 100000