2017-06-14 47 views
1

我想解析存储在数据库列中的一些数据到单个列中。数据可能会有所不同。我想为数据库列命名正在分析的值的名称。例如数= 12345的列应被叫号码,该列中的值应为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)但它分裂的数据,但不是我想要它。

回答

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) 
+0

谢谢。它看起来很可怕,但做我想做的事情! – user8159298

+0

如果没有人提供更好的解决方案,请不要忘记接受 –

+0

我很努力地用实际的数据库数据替换这些值 我试图做到这一点但无法让它工作 'with a(k,v)as( values(select id,parsing_column from mytable) )' 此外,因为我不知道parsing_column将包含什么,所以我无法创建临时表,因为我没有知道有多少列 我可以通过mytable获取最大数量的值:'select max(array_length(string_to_array(parsing_column,':'),1))from mytable;'但不确定如何使用(k,v)as(values(select my id,parsing_column from mytable))这个 – user8159298