I have a SQL table with the following data:
| Name | Colour | Shape |
| -------- | ------------------ | ---------------- |
| Bob | Blue, Green | Circle, Square |
| Phil | Yellow | |
| Steve | Green, Orange, Red | Square, Triangle |
I want to create a view/table of it which looks like:
| Name | Colour | Shape |
| -------- | -------| ---------|
| Bob | Blue | Circle |
| Bob | Blue | Square |
| Bob | Green | Circle |
| Bob | Green | Square |
| Phil | Yellow | |
| Steve | Green | Square |
| Steve | Green | Triangle |
| Steve | Orange | Square |
| Steve | Orange | Triangle |
| Steve | Red | Square |
| Steve | Red | Triangle |
Does anyone know how to do this?
I’ve tried to split the multiple value data into multiple rows using a distinct union, but it’s failing to generate the correct result.
2
Answers
You need to convert the comma-separated values into JSON format and then use the
JSON_TABLE()
function to separate the data in the Colour and Shape columns into multiple rows.Demo here
I made the assumption that you have “dictionaries” for color and shape. In this case, you have data to join with a comma-separated list.
Demo here
P.S. I didn’t care about spaces in CSV. This could make the query more verbose. I left only what expresses the essence. Sorry.