在PostgreSQL中如何将行转置为列?

6
有人知道如何在PostgreSQL中将行转置为列吗? 例如,我有以下表:-
  Period                T1            T2           Difference
----------           -------       --------        -----------
 MAR-2013             34525           319            34206
 AUG-2014             35632         14453            21179
 OCT-2014             28124         10082            18042
 JUN-2014             20571          9353            11218
 MAY-2015             44963         39097             5866
 FEB-2013              1941           127             1814
 JUL-2014             14510         12965             1545
 APR-2015             32446         30992             1454
 MAY-2014             13510         12136             1374
 APR-2014              8042          6967             1075
 JAN-2013              1107            86             1021
 DEC-2014             30764         30076              688
 SEP-2014              6886          6380              506
 MAR-2014              4695          4242              453

但是我需要的输出是:
Period  MAR-2013  AUG-2014 OCT-2014 JUN-2014 MAY-2015 FEB-2013 JUL-2014 APR-2015 MAY-2014  APR-2014  JAN-2013  DEC-2014  SEP-2014  MAR-2014 
------- --------  -------- -------  -------  -------  -------  -------  -------  -------   -------   -------   -------   -------   -------
  T1    34525     35632    28124     20571   44963  1941    14510     32446    13510      8042      1107      30764     6886      4695  
  T2      319     14453    10082      9353   39097       127    12965     30992    12136      6967        86      30076     6380      4242 
Diff    34206     21179    18042     11218    5866      1814     1545      1454     1374      1075      1021        688      506       453

1
重复的,解决方案在这里 https://dev59.com/YWAg5IYBdhLWcg3w5eVk - Kassav'
2
请查看这里这里这里这里的内容。 - user330315
嗨,这不是重复的... T1,T2不是列... 两个表... - Madhulandoll
1个回答

1
我为您写了一个简单的查询示例。这个过程包括两个部分。在 SECTION 1 中,每次我都会删除“表格”并重新创建它。该表仅用于查看JSON数据作为记录。
do 
$body$
declare
    per RECORD;
    v_sql text;
    v_del text;
begin 
    v_del = '';

    v_sql = 'DROP TABLE period_names; CREATE TABLE period_names (';
    FOR per IN
       SELECT distinct "period" from table1
    LOOP    
        v_sql = v_sql || v_del || '  "' || per."period"::text || '" varchar(100) NOT NULL';
        v_del = ', ';
    end loop;
    v_sql := v_sql || ');';
    execute v_sql;
   
end; 
$body$
LANGUAGE 'plpgsql';

第2节中,我使用真实的表格按期计算总和值,然后使用JSON类型将行显示为列(数据透视表)。

第2节

select pname as p_type, jsonb_populate_record(null::period_names, tt1.jsondata) as periods
from (
    select 'T1' as pname, jsonb_object_agg(tt."period", tt.t1) as jsondata from table1 as tt
    union all 
    select 'T2' as pname, jsonb_object_agg(tt."period", tt.t2) as jsondata from table1 as tt
    union all 
    select 'Dif' as pname, jsonb_object_agg(tt."period", tt.difference) as jsondata from table1 as tt
) tt1;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接