[英]Split column into multiple columns mysql
My dataframe has a column (numbers_selected) and for each row, it looks like this:我的 dataframe 有一列(numbers_selected),对于每一行,它看起来像这样:
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.最多有 6 列,因为一行中的数字不能超过 6 个。
At the end, the dataset should look like these:最后,数据集应如下所示:
1st Number第一个号码 | 2nd Number第二个号码 | 3rd Number第三个数字 | 4th Number第 4 号 | 5th Number第 5 号 | 6th Number第六号 |
---|---|---|---|---|---|
6 6 | 9 9 | 27 27 | Null Null | Null Null | Null Null |
2 2 | 3 3 | 6 6 | 8 8 | 30 30 | Null Null |
3 3 | 11 11 | 13 13 | 18 18 | Null Null | Null Null |
3 3 | 14 14 | 15 15 | 17 17 | 18 18 | 30 30 |
3 3 | 8 8 | 10 10 | 12 12 | 16 16 | Null Null |
3 3 | 7 7 | 8 8 | 27 27 | 29 29 | Null Null |
8 8 | 14 14 | 21 21 | Null Null | Null Null | Null Null |
bar酒吧
The query I am using is:我正在使用的查询是:
Select Week, number_selected from x. Select 周,number_selected from x。
Hope you can help me with these, thanks!希望您能帮我解决这些问题,谢谢!
How about a json approach? json 方法怎么样?
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.这通过使用字符串函数将破折号分隔的字符串转换为看起来像 json 数组的东西来工作。 Typically, '6-9-27'
becomes [6,9,27]
.通常, '6-9-27'
变为[6,9,27]
。 We can then use json accessor ->>
to bring each array element by index.然后我们可以使用 json 访问器->>
通过索引来获取每个数组元素。
Demo on DB Fiddle : 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.