Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split one string with commas into columns

For example, I have the following table:

| Block                       |
| abcdefgh,12kjkjkj,231wewoxyz|

How can I convert it into:

| Block1   | Block2   | Block3     |
| abcdefgh | 12kjkjkj | 231wewoxyz |

Note:

  • Each "Block" has a maximum of 8 commas (and hence can be split into 9 smaller blocks). The number of commas varies; some have 8 commas, some have 4, some have 7, etc. Each smaller block will occupy a column.

I use Presto, btw.

like image 607
Tai Ngo Avatar asked Dec 13 '22 14:12

Tai Ngo


1 Answers

Seems to me you would simply use split_part function to create your columns, like so:

SELECT
    split_part(Block, ',', 1) AS Block1,
    split_part(Block, ',', 2) AS Block2,
    split_part(Block, ',', 3) AS Block3,
    split_part(Block, ',', 4) AS Block4,
    split_part(Block, ',', 5) AS Block5,
    split_part(Block, ',', 6) AS Block6,
    split_part(Block, ',', 7) AS Block7,
    split_part(Block, ',', 8) AS Block8,
    split_part(Block, ',', 9) AS Block9
FROM
    your_table
like image 123
Nick Avatar answered Dec 17 '22 23:12

Nick