Skip to content
Advertisement

Transform table to one-hot encoding for many rows

I have a SQL table of the following format:

Now, I want to create a table with one ID per row, and multiple Cat’s in a row. My desired output looks as follows:

I have found:

Transform table to one-hot-encoding of single column value

However, I have more than 1000 Cat’s, so I am looking for code to write this automatically, rather than manually. Who can help me with this?

Advertisement

Answer

First let me transform the data you pasted into an actual table:

enter image description here (try sharing a table next time)

Now we can do some manual 1-hot encoding:

enter image description here

Now we want to write a script that will automatically create the columns we want:

enter image description here

That generates a string that you can copy paste into a query, that 1-hot encodes your arrays/rows:

enter image description here

And that’s exactly what the question was asking for. You can generate SQL with SQL, but you’ll need to write a new query using that result.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement