r/SQL • u/honkymcgoo • Jun 11 '26
Snowflake Help splitting string values into usable column
I have this really annoying request to turn a publication tree hierarchy into a visual one in tableau. In order to do this I need to turn a value in one column into multiple values and then match those new values to another column on another table. The column in question is called tree_path. Every tree path rolls up into a publication. So Guide to English as a publication would have a row for each tree_path value that rolls up to it.
The values inside look like this "A.B1.C1.D2' with a maximum depth of 13 parts each.
At each "." a new level of the tree is indicated, so in the above example A is the highest level, B1 is a child to A, C1 is a child to B1 and therefore also of A and so on.
I have tried split to table etc. and even just splitting it out into 13 columns but the issue is that each part correlates to a specific subject. So A might be English, B1 might be English Lit, C1 might be English Writing and so on. What I need to have is a useable column that I can join to the subject column to get that subject value.
Ultimately I want something that looks like this for however many tree_paths a publication has
Publication/tree_path/tree_path subject
So far I've had the most success with SPLIT_PART(Tree_path,'.',1) AS Depth1 just repeated 13 times to make 13 columns. But the issue there is that I would have to do 13 joins and then also it would be an extremely wide table.
I've tried LATERAL SPLIT_TO_TABLE(Tree_path,'.') but the problem there is that it creates single values for each split. So it will only create A, B1, C1 when really what I need is A, A.B1, A.B1.C1, etc.
Hopefully this makes sense to you guys, if not I'm happy to try and clarify.
1
u/TheGenericUser0815 Jun 11 '26
Been there, done that. My suggestion would be generating a self referencing table/view that represents the tree as the tree really is.
1
u/EveningConcept2524 Jun 11 '26
I would use the split column function and then export to excel/power query for the unpivot option. I’m not generally one to go from sql to power query but it has the easiest option for unpivoting data.
1
u/gumnos Jun 11 '26
While I don't have Snowflake at hand to test the corresponding functions, I'd start with something like this (done here using Postgres)
That
max(case …) as vNstuff might be simplifiable withPIVOTif Snowflake allows it.1
u/GRRRRRRRRRRRRRG Jun 11 '26
Does Snowflake have a recursion? You can split your string in recursion and save small parts and iteration depth as you go....
1
u/Ok_Carpet_9510 Jun 14 '26
Which database or data platform are you using?
Also, when do a select on that column, what comes back? Do you get json formatted data? If it is json, your database might support parsing and flattening the json. Python is another alternative.
0
u/millerlit Jun 11 '26
Maybe look into PIVOT
0
u/Regular-Employer-431 Jun 11 '26
I would post your entire question to grok.