在 Potgresql 中取消透视

gee*_*000 5 sql postgresql unpivot

如何在不使用 UNION 的情况下在 Postgresql 中取消透视?我有 100 多列,我正在寻找一种巧妙的方法来做到这一点。

给定表:

id    c1      c2      c3
1      X       Y       Z
2      A       B       C
3      Y       C       Z
Run Code Online (Sandbox Code Playgroud)

所需表:

id   col
1     X
1     Y
1     Z
2     A
2     B
2     C
3     Y
3     C
3     Z
Run Code Online (Sandbox Code Playgroud)

kli*_*lin 5

使用jsonb 函数:

select id, value as col
from my_table
cross join jsonb_each_text(to_jsonb(my_table))
where key <> 'id';

 id | value 
----+-------
  1 | X
  1 | Y
  1 | Z
  2 | A
  2 | B
  2 | C
  3 | Y
  3 | C
  3 | Z
(9 rows)
Run Code Online (Sandbox Code Playgroud)

Db<>小提琴。


在 Postgres 9.3 或 9.4 中使用to_json()json_each_text().

在 9.1 或 9.2 版本中安装hstore

create extension if not exists hstore;

select id, value as col
from my_table
cross join each(hstore(my_table))
where key <> 'id';
Run Code Online (Sandbox Code Playgroud)