How to split data from one column to three columns in another table? SQL

时光毁灭记忆、已成空白 提交于 2020-01-17 04:14:40

问题


I have table (inf) with two columns id_student and hobbies like this:

ID_student =  1      
Hobbies =   "music, cooking, bassguitar" 

and I want to copy the hobbies by splitting them to another table (hobbies) in three columns which contain the following columns:

ID_student   hobby1   hobby2     hobby3
1            music    cooking    bassguitar

how could I write something likethat in Postgres?


回答1:


There is many ways to do this. One way is using the string_to_array function:

INSERT INTO hobbies (id, hobby1, hobby2, hobby3) 
SELECT id,hobbies_array[1],hobbies_array[2],hobbies_array[3] FROM 
  (
    SELECT id,string_to_array(hobbies,',') AS hobbies_array 
    FROM inf
  ) AS foo;


来源:https://stackoverflow.com/questions/41087355/how-to-split-data-from-one-column-to-three-columns-in-another-table-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!