Gerar dinamicamente colunas para crosstab no PostgreSQL
Estou tentando criarcrosstab
consultas no PostgreSQL, de modo que ele gera automaticamentecrosstab
colunas em vez de codificá-lo. Eu escrevi uma função que dinamicamente gera a lista de colunas que eu preciso para o meucrosstab
inquerir. A ideia é substituir o resultado dessa função nocrosstab
consulta usando sql dinâmico.
Eu sei como fazer isso facilmente no SQL Server, mas meu conhecimento limitado do PostgreSQL está atrapalhando meu progresso aqui. Eu estava pensando em armazenar o resultado da função que gera a lista dinâmica de colunas em uma variável e usá-lo para construir dinamicamente a consulta sql. Seria ótimo se alguém pudesse me orientar sobre o mesmo.
-- Table which has be pivoted
CREATE TABLE test_db
(
kernel_id int,
key int,
value int
);
INSERT INTO test_db VALUES
(1,1,99),
(1,2,78),
(2,1,66),
(3,1,44),
(3,2,55),
(3,3,89);
-- This function dynamically returns the list of columns for crosstab
CREATE FUNCTION test() RETURNS TEXT AS '
DECLARE
key_id int;
text_op TEXT = '' kernel_id int, '';
BEGIN
FOR key_id IN SELECT DISTINCT key FROM test_db ORDER BY key LOOP
text_op := text_op || key_id || '' int , '' ;
END LOOP;
text_op := text_op || '' DUMMY text'';
RETURN text_op;
END;
' LANGUAGE 'plpgsql';
-- This query works. I just need to convert the static list
-- of crosstab columns to be generated dynamically.
SELECT * FROM
crosstab
(
'SELECT kernel_id, key, value FROM test_db ORDER BY 1,2',
'SELECT DISTINCT key FROM test_db ORDER BY 1'
)
AS x (kernel_id int, key1 int, key2 int, key3 int); -- How can I replace ..
-- .. this static list with a dynamically generated list of columns ?