1
如何在不使用UNION的情況下在Postgresql中轉義?我有超過100列,我正在尋找一個乾淨的方式來做到這一點。Potgresql中的Unpivot
鑑於表:
id c1 c2 c3
1 X Y Z
2 A B C
3 Y C Z
所需的表:
id col
1 X
1 Y
1 Z
2 A
2 B
2 C
3 Y
3 C
3 Z
如何在不使用UNION的情況下在Postgresql中轉義?我有超過100列,我正在尋找一個乾淨的方式來做到這一點。Potgresql中的Unpivot
鑑於表:
id c1 c2 c3
1 X Y Z
2 A B C
3 Y C Z
所需的表:
id col
1 X
1 Y
1 Z
2 A
2 B
2 C
3 Y
3 C
3 Z
select id, value as col
from my_table,
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)
在Postgres 9.3和9.4中使用to_json()
和json_each_text()
。
在版本9.1或9.2安裝hstore:
create extension if not exists hstore;
select id, value
from (
select id, (each(hstore(my_table))).key, (each(hstore(my_table))).value
from my_table
) s
where key <> 'id';
謝謝@klin。我收到以下錯誤:函數to_jsonb(my_table)不存在。你知道爲什麼會發生這種情況嗎? – geek2000
該功能在Postgres 9.5+中可用;如果你有版本9.3或9.4,使用'json_each_text()'和'to_json()'。 – klin
謝謝,但得到相同的錯誤。難道我的postgres安裝失去了一些東西? – geek2000