简体   繁体   中英

Splitting a table column into multiple columns in mysql

my table looks as follows ( i populate it from a spreadsheet); for a easy manipulation i need to seperate function Code AA column into multiple columns.Values in that column are joined with,. Separate them with comma seperated values.

Eg:
Function CodeAA1    Function CodeAA2  ..
03                    04             ..

How can i do that in mysql?

Mysql workbench version 6.3 no limiton those comma seperated column. I expect it goes 1 to 10. 在此处输入图像描述

Some combination of 'word' count, CASE and SUBSTRING_INDEX should get your expected result. Something like below:

SELECT fcaa,
       CASE WHEN t_cnt >= 1 THEN SUBSTRING_INDEX(fcaa, "," ,1) END AS Fcaa1,
       CASE WHEN t_cnt >= 2 THEN SUBSTRING_INDEX(SUBSTRING_INDEX(fcaa, "," ,2), "," ,-1) END AS Fcaa2,
       CASE WHEN t_cnt >= 3 THEN SUBSTRING_INDEX(SUBSTRING_INDEX(fcaa, "," ,3), "," ,-1) END AS Fcaa3,
       CASE WHEN t_cnt >= 4 THEN SUBSTRING_INDEX(SUBSTRING_INDEX(fcaa, "," ,4), "," ,-1) END AS Fcaa4,
       CASE WHEN t_cnt >= 5 THEN SUBSTRING_INDEX(SUBSTRING_INDEX(fcaa, "," ,5), "," ,-1) END AS Fcaa5,
       CASE WHEN t_cnt >= 6 THEN SUBSTRING_INDEX(SUBSTRING_INDEX(fcaa, "," ,6), "," ,-1) END AS Fcaa6,
       CASE WHEN t_cnt >= 7 THEN SUBSTRING_INDEX(SUBSTRING_INDEX(fcaa, "," ,7), "," ,-1) END AS Fcaa7,
       CASE WHEN t_cnt >= 8 THEN SUBSTRING_INDEX(SUBSTRING_INDEX(fcaa, "," ,8), "," ,-1) END AS Fcaa8,
       CASE WHEN t_cnt >= 9 THEN SUBSTRING_INDEX(SUBSTRING_INDEX(fcaa, "," ,9), "," ,-1) END AS Fcaa9,
       CASE WHEN t_cnt >= 10 THEN SUBSTRING_INDEX(SUBSTRING_INDEX(fcaa, "," ,10), "," ,-1) END AS Fcaa10
FROM
(SELECT `yourColumn` AS fcaa,
        (LENGTH(`yourColumn`)-LENGTH(REPLACE(`yourColumn`, "," ,'')))+1 AS t_cnt 
 FROM   yourTable) A;

  1. The first part is to count how many 'word' in the column row. Hence the usage of whole LENGTH() of the data subtract with LENGTH() without spaces. We add 1 at the end because if you see one of the example '03,04,07,08,12,13' it has 6 occurrence ('word') but if we do (LENGTH(yourColumn)-LENGTH(REPLACE(yourColumn,',',''))) without +1 , we will get 5 count only.

  2. The second part is using CASE with SUBSTRING_INDEX . So when count('t_cnt' - is the word count) matches certain value, then we use corresponding SUBSTRING_INDEX function to return the value.

I'm sure there are better ways of doing this but I happen to be doing the same thing before and this method seems like a long one but it works for me. Hopefully, it'll work for you too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM