Creating a table based on contents of table column

时间:2017-06-19 13:59:47

标签: postgresql

I have the following sql, when run produces this table

select id, trim(s.my_data) as my_data from my_table t, unnest(string_to_array(t.column_to_parse, ':')) s(my_data)

id | my_data
------------
1  | first
1  | last=bbb
1  | middle=ccc
1  | bottle=ddd

I now want to create a table using the contents of my_data and split the my_data column so the first part before the '=' becomes the column name

e.g.

id | first | last | middle | bottle
-------------------------------------
1  |       | bbb  | ccc    | ddd 

I cannot hard code the values, they will be different each time, I need to create the column name from the table column value

How do I accomplish this?

1 个答案:

答案 0 :(得分:0)

SELECT id,
       split_part(parsed[1], '=', 2) AS first,
       split_part(parsed[2], '=', 2) AS last,
       split_part(parsed[3], '=', 2) AS middle,
       split_part(parsed[4], '=', 2) AS bottle
FROM (SELECT id,
             string_to_array(column_to_parse, ':') parsed
      FROM my_table) q;

 id | first | last | middle | bottle
----+-------+------+--------+--------
  1 |       | bbb  | ccc    | ddd
(1 row)