将数据库列解析为单个列

时间:2017-06-14 09:19:09

标签: postgresql

我正在尝试将存储在数据库列中的一些数据解析为单个列。数据的长度可能不同。我想将数据库列命名为要解析的值的名称。例如number = 12345该列应该被称为number,列中的值应该是12345

存储在列中的数据示例:

id  text
___________________________________________________________________________
1   Re: Fwd: number=12345:bottle=glass:water=sparkling:food=chocolate
2   number=223344:bottle=plastic:water=still:food=sweets:biscuit=digestive

我想要的是以下内容:

id Re  Fwd number  bottle  water       food        biscuit
__________________________________________________________________
1   Re  Fwd 12345   glass   sparkling   chocolate null
2   null null 223344  plastic still       sweets      digestive    

我已经尝试了(select string_to_array (text, ':') from my_table),但它分割数据但不是我想要的。

1 个答案:

答案 0 :(得分:0)

要插入的表:

create table s201 (id int,Re text, Fwd text,number int, bottle text, water text,      food  text,      biscuit text);

查询:

with pre as (
with a(k,v) as (
    values (1,'Re: Fwd: number=12345:bottle=glass:water=sparkling:food=chocolate'),(2,'number=223344:bottle=plastic:water=still:food=sweets:biscuit=digestive')
  )
  , col(s,n) as (select * from unnest(array['Re','Fwd','number','bottle','water','food','biscuit'])  with ordinality c (s,n))
select s,n,k, case when o not like '%=%' then trim(o) else  split_part(trim(o),'=',2) end c
from col
join a on true
left outer join unnest(string_to_array(a.v,':')) with ordinality t (o,i) on split_part(trim(o),'=',1) = s
)
, agg as (
select k, array_agg(c order by n) a
from pre
group by k
)
insert into s201
select k,a[1],a[2],a[3]::int,a[4],a[5],a[6],a[7]
from agg;
  

INSERT 0 2

检查:

select * from s201;
 id | re | fwd | number | bottle  |   water   |   food    |  biscuit
----+----+-----+--------+---------+-----------+-----------+-----------
  1 | Re | Fwd |  12345 | glass   | sparkling | chocolate |
  2 |    |     | 223344 | plastic | still     | sweets    | digestive
(2 rows)