在PostgreSQL中动态生成交叉表的列

s5a0g9ez  于 2023-11-18  发布在  PostgreSQL
关注(0)|答案(4)|浏览(114)

我尝试在PostgreSQL中创建crosstab查询,以便它自动生成crosstab列,而不是硬编码它。我写了一个函数,动态生成crosstab查询所需的列列表。其想法是使用动态SQL在crosstab查询中替换此函数的结果。
如何在PostgreSQL中做到这一点?

-- 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 ?

字符串

llew8vvj

llew8vvj1#

你可以使用提供的C函数crosstab_hash
说明书在这方面不是很清楚,提到了at the end of the chapter on crosstab() with two parameters:
您可以创建预定义的函数,以避免在每个查询中写出结果列名和类型。请参阅上一节中的示例。这种形式的crosstab的底层C函数名为crosstab_hash
举个例子:

CREATE OR REPLACE FUNCTION f_cross_test_db(text, text)
  RETURNS TABLE (kernel_id int, key1 int, key2 int, key3 int)
  AS '$libdir/tablefunc','crosstab_hash' LANGUAGE C STABLE STRICT;

字符串
电话:

SELECT * FROM f_cross_test_db(
      'SELECT kernel_id, key, value FROM test_db ORDER BY 1,2'
     ,'SELECT DISTINCT key FROM test_db ORDER BY 1');


请注意,您需要为每个具有不同返回类型的crosstab函数创建一个不同的crosstab_hash函数。
相关:

  • PostgreSQL行到列

您的 * 函数生成列列表 * 相当复杂,结果不正确(kernel_id之后缺少int),可以用以下SQL查询替换:

SELECT 'kernel_id int, '
       || string_agg(DISTINCT key::text, ' int, '  ORDER BY key::text)
       || ' int, DUMMY text'
FROM   test_db;


而且无论如何都不能动态使用。

iibxawm4

iibxawm42#

我知道这是一个老职位,但在同一问题上挣扎了一段时间。

**我的问题陈述:**我有一个字段中有多个值的表,并希望创建一个每行有40多个列标题的交叉表查询。

我的解决方案是创建一个函数,该函数循环遍历表列,以获取我希望用作交叉表查询中列标题的值。
在这个函数中,我可以创建交叉表查询。在我的用例中,我将这个交叉表结果添加到一个单独的表中。
例如

CREATE OR REPLACE FUNCTION field_values_ct ()
 RETURNS VOID AS $$
DECLARE rec RECORD;
DECLARE str text;
BEGIN
str := '"Issue ID" text,';
   -- looping to get column heading string
   FOR rec IN SELECT DISTINCT field_name
        FROM issue_fields
        ORDER BY field_name
    LOOP
    str :=  str || '"' || rec.field_name || '" text' ||',';
    END LOOP;
    str:= substring(str, 0, length(str));

    EXECUTE 'CREATE EXTENSION IF NOT EXISTS tablefunc;
    DROP TABLE IF EXISTS temp_issue_fields;
    CREATE TABLE temp_issue_fields AS
    SELECT *
    FROM crosstab(''select issue_id, field_name, field_value from issue_fields order by 1'',
                 ''SELECT DISTINCT field_name FROM issue_fields ORDER BY 1'')
         AS final_result ('|| str ||')';
END;
$$ LANGUAGE plpgsql;

字符串

wj8zmpe1

wj8zmpe13#

@erwin-brandstetter:如果你总是返回一个JSON类型的转换结果,那么函数的返回类型就不是问题。
下面是我提出的函数:

CREATE OR REPLACE FUNCTION report.test(
    i_start_date TIMESTAMPTZ,
    i_end_date TIMESTAMPTZ,
    i_interval INT
    ) RETURNS TABLE (
    tab JSON
    ) AS $ab$
DECLARE
    _key_id TEXT;
    _text_op TEXT = '';
    _ret JSON;
BEGIN
    -- SELECT DISTINCT for query results
    FOR _key_id IN
    SELECT DISTINCT at_name
      FROM report.company_data_date cd 
      JOIN report.company_data_amount cda ON cd.id = cda.company_data_date_id 
      JOIN report.amount_types at ON cda.amount_type_id  = at.id 
     WHERE date_start BETWEEN i_start_date AND i_end_date
       AND interval_type_id = i_interval
    LOOP
    -- build function_call with datatype of column
        IF char_length(_text_op) > 1 THEN
            _text_op := _text_op || ', ' || _key_id || ' NUMERIC(20,2)';
        ELSE
            _text_op := _text_op || _key_id || ' NUMERIC(20,2)';
        END IF;
    END LOOP;
    -- build query with parameter filters
    RETURN QUERY
    EXECUTE '
        SELECT array_to_json(array_agg(row_to_json(t)))
          FROM (
        SELECT * FROM crosstab(''SELECT date_start, at.at_name,  cda.amount ct 
          FROM report.company_data_date cd 
          JOIN report.company_data_amount cda ON cd.id = cda.company_data_date_id 
          JOIN report.amount_types at ON cda.amount_type_id  = at.id 
         WHERE date_start between $$' || i_start_date::TEXT || '$$ AND $$' || i_end_date::TEXT || '$$ 
           AND interval_type_id = ' || i_interval::TEXT || ' ORDER BY date_start'') 
            AS ct (date_start timestamptz, ' || _text_op || ')
             ) t;';
END;
$ab$ LANGUAGE 'plpgsql';

字符串
所以,当你运行它时,你会得到JSON格式的动态结果,你不需要知道有多少值被旋转:

select * from report.test(now()- '1 week'::interval, now(), 1);
                                                                                                                     tab                                                                                                                      
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 [{"date_start":"2015-07-27T08:40:01.277556-04:00","burn_rate":0.00,"monthly_revenue":5800.00,"cash_balance":0.00},{"date_start":"2015-07-27T08:50:02.458868-04:00","burn_rate":34000.00,"monthly_revenue":15800.00,"cash_balance":24000.00}]
(1 row)

编辑:如果你的交叉表中有混合数据表,你可以添加逻辑来查找每一列,如下所示:

SELECT a.attname as column_name, format_type(a.atttypid, a.atttypmod) AS data_type 
    FROM pg_attribute a 
    JOIN pg_class b ON (a.attrelid = b.relfilenode) 
    JOIN pg_catalog.pg_namespace n ON n.oid = b.relnamespace 
   WHERE n.nspname = $$schema_name$$ AND b.relname = $$table_name$$ and a.attstattarget = -1;"

xzv2uavs

xzv2uavs4#

here描述的方法对我来说很有效。而不是直接检索pivot表。更简单的方法是让函数生成SQL查询字符串。根据需要动态执行结果SQL查询字符串。
动态查询模式简介:

DO $$ BEGIN
DROP TABLE IF EXISTS temp_pivot;
EXEUTE(SELECT
  'CREATE TEMPORARY TABLE temp_pivot AS SELECT * FROM crosstab(
   ''$value_query'', ''$cat_query'') AS ct (rn text, "'
   || string_agg(cat_col, '" text,"') || '" text);'
   FROM $cat_query 
); 
END $$;
SELECT * FROM temp_pivot;

字符串

相关问题