更新并将逗号分隔的列数据拆分为其他列

时间:2016-09-16 09:12:29

标签: postgresql postgresql-9.1

表格如下

id, column, col1, col2
1, abc-def, 

基本上我需要拆分column1并更新col1和col2

select split_part(column, '-', 1) as col1, split_part(column, '-', 2) as col2 from table

如何使用id。

同时更新和选择

2 个答案:

答案 0 :(得分:0)

# CREATE TEMPORARY TABLE tmp_split (id SERIAL PRIMARY KEY, c0 VARCHAR(32), c1 VARCHAR(16), c2 VARCHAR(16));
CREATE TABLE

# INSERT INTO tmp_split (c0) VALUES ('one-two'), ('three-four');
INSERT 0 2

# SELECT * FROM tmp_split;
 id |     c0     | c1 | c2 
----+------------+----+----
  1 | one-two    |    | 
  2 | three-four |    | 
(2 rows)

# UPDATE tmp_split SET c1 = split_part(c0, '-', 1), c2 = split_part(c0, '-', 2);
UPDATE 2

# SELECT * FROM tmp_split;
 id |     c0     |  c1   |  c2  
----+------------+-------+------
  1 | one-two    | one   | two
  2 | three-four | three | four
(2 rows)

答案 1 :(得分:0)

update the_table
  set col1 = split_part(column, '-', 1), 
      col2 = split_part(column, '-', 2)