I need to split comma separated values and pivot them to create a 2 column mapping view.
The hard part: The first item in each list is the mapping key for all items in that list (including itself).
For example, given this list (in one column):
Related_Fruits |
---|
Banana, Watermelon, Kiwi |
Apple |
Mango, Orange |
...this is the desired output (a mapping table):
Fruit_Parent | Fruit_Child |
---|---|
Banana | Banana |
Banana | Watermelon |
Banana | Kiwi |
Apple | Apple |
Mango | Mango |
Mango | Orange |
Here is some test ddl/data
CREATE TABLE #test(Related_Fruits varchar(50))
insert into #test Values ('Apple')
insert into #test Values ('Banana, Watermelon, Kiwi')
insert into #test Values ('Mango, Orange')
select * from #test
This is as close as I've gotten so far, but the first column includes ALL values in the list, not just the first one. And when I try to parse out just the first value (substring and charindex), then the cross apply and string_split don't work.
Also, there are spaces after the commas in the list, which indent each child by one space (doesn't show in this forum due to formatting) which also need to be removed.
Select *
From #test
Cross Apply String_Split(Related_Fruits,',')
Result:
Related_Fruits | value |
---|---|
Apple | Apple |
Banana, Watermelon, Kiwi | Banana |
Banana, Watermelon, Kiwi | Watermelon |
Banana, Watermelon, Kiwi | Kiwi |
Mango, Orange | Mango |
Mango, Orange | Orange |
Any suggestions?