Skip to content
Advertisement

Create recursive query in Snowflake with a Left Join condition?

I am trying to create a recursive query that relies on a LEFT JOIN condition, but I am not sure if it is possible, especially in Snowflake.

I have three tables: ITEM, ITEMHIERARCHY, and ITEMVALUE

My goal is to return a list of all ITEMs with values and sub-item values rolled-up:

Note that even though Item6 is a roll-up from Item4 because there is already a given value of 77.7 on the ITEMVALUE table, the roll-up is ignored.

Here is my attempt at a failing recursive query due to the LEFT JOIN in the UNION ALL clause:

The goal of the query is to first get all top level ITEMs from the ITEM table, search for a corresponding value on the ITEMVALUE table, and, if none is found, join to the ITEMHIERARCHY Table to retrieve all SUBITEMs that compose the top level ITEMs. I would then like to recursively search on the ITEMVALUE table for a SUBITEM-VALUE match, or, if none is found, retrieve the SUBITEMs from the ITEMHIERARCHY table.

The first set of LEFT-JOINs work, but not the ones under the UNION ALL giving me the error:

Is there a better way to do what I am trying to do in Snowflake or am I not thinking about this correctly?

Currently I manually wrote out the recursive layers to 5 levels meaning I have to add a level if the ITEMHIERARCHY table becomes more complex.

Advertisement

Answer

Here’s a working example that gives you the results you expected. You can also view it on SQLFiddle.

RESULTS:

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