Postgresql-使用Crosstab或其他方法进行数据透视?

时间:2019-03-15 11:09:12

标签: postgresql pivot crosstab

我有下表:

enter image description here

我要对此进行调整,并得到以下结果:

  Table_name        Column_name      Values         ddmf_etl_id
"PROFITCENTERID"    "CO_AREA"       "DE02"           16807487
"PROFITCENTERID"    "PROFIT_CTR"    "0000001119"     16807487
"PROFITCENTERID"    "CO_AREA"       "DE02"           16807488
"PROFITCENTERID"    "PROFIT_CTR"    "0000001120"     16807488

不幸的是,我无法通过以下选择来执行此操作,因为CROSSTAB的参数数量有限(3):

SELECT  'PROFITCENTERID' AS table_name,t.*
FROM   

crosstab(

        'SELECT unnest(''{CO_AREA,PROFIT_CTR}''::text[]) AS col
             , row_number() OVER ()
             , unnest(ARRAY[CO_AREA::text,PROFIT_CTR::text]) AS val
        FROM   "1".PROFITCENTER_PROFITCENTERID'

   ) t (column_name text,  values text);

select语句的结果(错误):

enter image description here

在Postgresql中,交叉表还有其他替代方法吗?也许可以通过Crosstab做到这一点?

感谢您的帮助!谢谢!

1 个答案:

答案 0 :(得分:1)

使用unnest()将每一行加倍并选择适当的值:

select
    'profitcenterid' as table_name,
    unnest(array['co_area', 'profit_ctr']) as column_name,
    unnest(array[co_area, profit_ctr]) as value,
    ddmf_etl_id as ddmf_etl_id
from profitcenter_profitcenterid

   table_name   | column_name |   value    | ddmf_etl_id 
----------------+-------------+------------+-------------
 profitcenterid | co_area     | de02       |    16807487
 profitcenterid | profit_ctr  | 0000001119 |    16807487
 profitcenterid | co_area     | de02       |    16807488
 profitcenterid | profit_ctr  | 0000001120 |    16807488
(4 rows)    

Live demo in rextester.

但是,这对于获得预期的json结果没有多大帮助。您希望获得任意键名,因此无法根据子查询结果自动生成对象。可以使用原始jsonb_build_object()创建它们:

select to_jsonb(s)
from (
    select
        'profitcenterid' as table_name,
        17 as type,
        '' as value,
        jsonb_build_array(
            jsonb_build_object('name', 'co_area', 'value', co_area, 'type', 0, 'children', '[]'::jsonb),
            jsonb_build_object('name', 'profit_ctr', 'value', profit_ctr, 'type', 0, 'children', '[]'::jsonb)
        ) as children
    from profitcenter_profitcenterid
    ) s

Example in rextester.

附带说明,预期的结构似乎不必要地复杂,简单是一种优点。