简体   繁体   中英

Split column into multiple columns mysql

My dataframe has a column (numbers_selected) and for each row, it looks like this:

1. 6-9-27
2. 2-3-6-8-30
3. 3-11-13-18
4. 3-14-15-17-18-30
5. 3-8-10-12-16
6. 3-7-8-27-29
7. 8-14-21

As you can see each row can have different amount of numbers.

What I am looking for is to see if it is possible to create a column for each of these numbers. There will be up to 6 columns as it is not possible to have more than 6 numbers in a row.

At the end, the dataset should look like these:

1st Number 2nd Number 3rd Number 4th Number 5th Number 6th Number
6 9 27 Null Null Null
2 3 6 8 30 Null
3 11 13 18 Null Null
3 14 15 17 18 30
3 8 10 12 16 Null
3 7 8 27 29 Null
8 14 21 Null Null Null

bar

The query I am using is:

Select Week, number_selected from x.

Hope you can help me with these, thanks!

How about a json approach?

select week,
    js ->> '$[0]' as num1,
    js ->> '$[1]' as num2,
    js ->> '$[2]' as num3,
    js ->> '$[3]' as num4,
    js ->> '$[4]' as num5,
    js ->> '$[5]' as num6
from (
    select t.*, concat('[', replace(numbers_selected, '-', ','), ']') as js
    from mytable t
) t

This works by using string functions to convert the dash-separated string to something that looks like a json array. Typically, '6-9-27' becomes [6,9,27] . We can then use json accessor ->> to bring each array element by index.

Demo on DB Fiddle :

week | num1 | num2 | num3 | num4 | num5 | num6
---: | :--- | :--- | :--- | :--- | :--- | :---
   1 | 6    | 9    | 27   | null | null | null
   2 | 2    | 3    | 6    | 8    | 30   | null
   3 | 3    | 11   | 13   | 18   | null | null
   4 | 3    | 14   | 15   | 17   | 18   | 30  
   5 | 3    | 8    | 10   | 12   | 16   | null
   6 | 3    | 7    | 8    | 27   | 29   | null
   7 | 8    | 14   | 21   | null | null | null

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