将行拆分为具有不同列的表

时间:2019-01-31 16:24:36

标签: sql postgresql

你好,我有一个表,其中包含字符串数组:

----------------------------------------------------------
"Continent": "Europe", "Nation": "Italy", "City": "Rome"
"Continent": "Asia", "Nation": "China", "City": "Beijing"
"Continent": "Europe", "Nation": "France", "City": "Paris"
"Continent": "Africa", "Nation": "Tunisia", "City": "Tunis"
-----------------------------------------------------------

我想这样解决:

ID | CONTINENT  |  NATION | CITY
-----------------------------------------------------
1  | Africa     |  Tunisia| Tunis
2  | Europe     |  Italy  | Rome
3  | Europe     |  France | Paris
4  | Asia       |  China  | Beijing

如何在POSTGRESQL中做到这一点?

2 个答案:

答案 0 :(得分:3)

您的字符串值接近于JSON。通过将其用json括起来将其强制转换为{},只需使用->>运算符即可将各个元素提取为列。

with js as
(
select  ('{'||str||'}')::json as j from t
) select j->>'Continent' as Continent,
         j->>'Nation'  as Nation,
         j->>'City' as City FROM js;

Demo

答案 1 :(得分:0)

这比公认的答案要优雅得多,但是是为了共享其他选择:

select
  row_number() over (partition by 1) as id,
  substring ((regexp_split_to_array (rowdata, ','))[1] from ': "(.+)"$') as Continent,
  substring ((regexp_split_to_array (rowdata, ','))[2] from ': "(.+)"$') as Nation,
  substring ((regexp_split_to_array (rowdata, ','))[3] from ': "(.+)"$') as City
from t1