'Problem returning dynamic crosstab function

Im struggeling since a long time with a dynamic crosstab query.

After a lot of research i came across with a function that works.

CREATE OR REPLACE FUNCTION custom.test_crosstab_dynamics(symb character varying(2)) RETURNS text AS
$$
    DECLARE
        tmp character varying(1000);
        cts character varying(1000);
        s character varying(1000);
        r RECORD;
    BEGIN
        tmp:= '';
        s:=null;
        cts:='("ref" text,"street" text,"city" text,';
        FOR r IN SELECT distinct year  FROM custom.grem_verg(110736) ORDER BY year
            LOOP
                IF r.year IS NOT NULL AND r.year <> (SELECT year FROM custom.grem_verg(110736) ORDER BY year DESC LIMIT 1) THEN
                    tmp := tmp || '(''' || r.year || '''),';
                    cts:=cts ||'"'|| r.year ||'"'|| ' numeric(10,0),';
                ELSE
                    tmp := tmp || '(''' || r.year || ''')';
                    cts:=cts ||'"'|| r.year ||'"'|| ' numeric(10,0))';
                END IF;     
            END LOOP;
            
            s:='SELECT * FROM crosstab(''';
                s:=s || 'select ref, street,city,year,nettomiete from custom.grem_verg(110736) order by 1,4''';  
                    s:=s ||',';
                    s:=s || symb || 'VALUES' || tmp || symb ||') AS ct' || cts;
        RETURN s;
    END;
$$
LANGUAGE plpgsql;

If i call the function like this

SELECT * FROM custom.test_crosstab_dynamics('$$')

This is what i get in return. enter image description here

To get to my wished output i need to copy and paste the Value and manually execute the query inside.

I want to be able call the custom.text_crostab_dynamics function and get my wished output directly. Like in a table.

Iv'e tried to rewrite the function to return a table and so on but without success. I have reached my limit and hope someone can help me.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source