How do I turn the query below into a temporary view? Everything I've tried returns the text of the generated query (second quoted code block). "Everything" includes...
- Wrapping the 1st query in another
SELECT * FROM... - Doing a
CREATE TEMP VIEWas the 1st query, or as a select of the first query, or as just the text without any selects - A
CREATE FUNCTIONwith the 1st query, thenCREATE TEMP VIEWof the function
I can't really wrap it into a plpgsql function, because it's a dynamic query for a crosstab of a table containing an arbitrary number of rows, which crosstabs to an arbitrary number of columns. Thus, I can't define the return type for the plpgsql function.
The code below is taken directly from Erwin Brandstetter's answer to Transpose a table by converting columns to rows.
1st query:
SELECT 'SELECT * FROM crosstab( $ct$SELECT u.attnum, t.rn, u.val FROM (SELECT row_number() OVER () AS rn, * FROM ' || attrelid::regclass || ') t , unnest(ARRAY[' || string_agg(quote_ident(attname) || '::text', ',') || ']) WITH ORDINALITY u(val, attnum) ORDER BY 1, 2$ct$ ) t (attnum bigint, ' || (SELECT string_agg('r'|| rn ||' text', ', ') FROM (SELECT row_number() OVER () AS rn FROM tbl) t) || ')' AS sql FROM pg_attribute WHERE attrelid = 'tbl'::regclass AND attnum > 0 AND NOT attisdropped GROUP BY attrelid;Operating with attnum instead of actual column names. Simpler and faster. Join the result to pg_attribute once more or integrate column names like in the pg 9.3 example [of Erwin Brandstetter's answer to Transpose a table by converting columns to rows].
Generates a query of the form:
2nd Query:
SELECT * FROM crosstab( $ct$ SELECT u.attnum, t.rn, u.val FROM (SELECT row_number() OVER () AS rn, * FROM tbl) t , unnest(ARRAY[sl_no::text,username::text,designation::text,salary::text]) WITH ORDINALITY u(val, attnum) ORDER BY 1, 2$ct$ ) t (attnum bigint, r1 text, r2 text, r3 text, r4 text);
viewthat can show a different number of columns each time youselectfrom it, based on the dynamic query - you can't have that. The structure of the view needs to be known at call time the same as the output of the function does.countis rather stable. So for an entire session, theselectof theviewwould always have the same columns. The columns of thevieware calculated in the 1st query bySELECT string_agg('r'|| rn ||' text', ', ') FROM (SELECT row_number() OVER () AS rn FROM tbl) tSo what I want is to run the 1st query once at the beginning of the session, generate the 2nd query,CREATE TEMP VIEWonce, and then use that temporary static view until logout.