Mad*_*oll 5 sql postgresql pivot
有谁知道如何在 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
Run Code Online (Sandbox Code Playgroud)
但我需要输出为
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
Run Code Online (Sandbox Code Playgroud)
例如,我写了一个简单的查询。该过程由 2 个部分组成。每次SECTION 1我删除“表”并重新创建它。该表仅用于查看 JSON 数据作为记录。
SECTION 1:
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';
Run Code Online (Sandbox Code Playgroud)
我SECTION 2使用真实表按周期计算总和值,然后使用 JSON 类型将行显示为列(数据透视表)
SECTION 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;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7529 次 |
| 最近记录: |