我正在尝试在PostgreSQL中创建查询,使其自动生成列而不是硬编码。我编写了一个函数来动态生成我查询所需的列清单。我的想法是使用动态SQL将此函数的结果替换到查询中。虽然我知道如何在SQL Server中轻松完成这项工作,但我对PostgreSQL的了解有限,这使我的进展受阻。我考虑将生成动态列列表的函数的结果存储到变量中,并使用它动态构建SQL查询。如果有人能指导我做出相应操作,那将非常棒。
-- 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 ?
RETURNS TABLE (kernel_id int, key1 int, key2 int, key3 int)
。这难道不是正是 OP 想要避免的吗? - Vikas Prasad