如何在没有编写函数的情况下在postgresql中进行透视或交叉处理?

时间:2018-05-11 19:54:19

标签: postgresql pivot crosstab

我有一个看起来像这样的数据集:

gotta pivot

我想在一行汇总所有co值,因此最终结果如下所示:

enter image description here

看起来很简单,对吗?只需使用crosstab编写查询,如this answer中所述。问题是需要我CREATE EXTENSION tablefunc;并且我没有对我的数据库的写访问权。

有人可以推荐替代品吗?

3 个答案:

答案 0 :(得分:3)

条件聚合:

SELECT co,
  MIN(CASE WHEN ontology_type = 'industry' THEN tags END) AS industry,
  MIN(CASE WHEN ontology_type = 'customer_type' THEN tags END) AS customer_type, 
  -- ...
FROM tab_name
GROUP BY co

答案 1 :(得分:0)

您可以使用 DO 生成并使用交叉表列生成 PREPARE 您自己的 SQL ,然后执行

-- replace tab_name to yours table name

DO $$
DECLARE
  _query text;
  _name text;
BEGIN
  _name := 'prepared_query';
  _query := '
    SELECT co
        '||(SELECT ', '||string_agg(DISTINCT 
                    ' string_agg(DISTINCT 
                                CASE ontology_type WHEN '||quote_literal(ontology_type)||' THEN tags 
                                ELSE NULL 
                                END, '',''
                                ) AS '||quote_ident(ontology_type),',') 
            FROM tab_name)||'
    FROM tab_name
    GROUP BY co
    ';

    BEGIN
        EXECUTE 'DEALLOCATE '||_name;
    EXCEPTION
        WHEN invalid_sql_statement_name THEN
    END;

    EXECUTE 'PREPARE '||_name||' AS '||_query;
END
$$;

EXECUTE prepared_query;

答案 2 :(得分:0)

通过使用枢轴,我们可以实现您所需的输出

SELECT co
    ,industry
    ,customer_type
    ,product_type
    ,sales_model
    ,stage
FROM dataSet
PIVOT(max(tags) FOR ontologyType IN (
            industry
            ,customer_type
            ,product_type
            ,sales_model
            ,stage
            )) AS PVT