postrgresql split single column to multiple columns based on name and value

时间:2017-10-12 09:43:03

标签: sql postgresql split

My table ABC contains only 1 column as below ::

name=>countryvalue=>India name=>populationvalue=>10000000 name=>rankvalue=>25 name=>typevalue=>developing 
name=>countryvalue=>USA name=>populationvalue=>100000 name=>rankvalue=>3 name=>typevalue=>developed 
name=>countryvalue=>China name=>populationvalue=>15000000 name=>rankvalue=>5 name=>typevalue=>developed

My expected output is like below:

country     population  rank    type  
India       10000000     25     developing
USA         100000        3     developed 
China       15000000      5     developed

1 个答案:

答案 0 :(得分:0)

smth like?

f=# with tbl(cl) as (select 'name=>countryvalue=>India name=>populationvalue=>10000000 name=>rankvalue=>25 name=>typevalue=>developing'::text)
, part as (select split_part(cl,'name=>',2) a, split_part(cl,'name=>',3) b, split_part(cl,'name=>',4) c, split_part(cl,'name=>',5) d from tbl)
select split_part(a,'=>',2),split_part(b,'=>',2),split_part(c,'=>',2),split_part(d,'=>',2) from part;
 split_part | split_part | split_part | split_part
------------+------------+------------+------------
 India      | 10000000   | 25         | developing
(1 row)

of course if the order of columns is not granted - you need to elaborate the delimiter

or more pervert but neat way:

f=# create table rt(country text, population text, rank int, type text);
CREATE TABLE
f=# with hs as (select hstore_to_json(substr(replace(replace('name=>countryvalue=>India name=>populationvalue=>10000000 name=>rankvalue=>25 name=>typevalue=>developing',' name=>',','),'value=>','=>'),7)::hstore) a)
select j.* from hs, json_populate_record(null::rt, a) j;
 country | population | rank |    type
---------+------------+------+------------
 India   | 10000000   |   25 | developing
(1 row)

for this you will need hstore extension, type prepared (or table) and enthusiasm