Skip to content
Advertisement

Oracle SQL hierarchical query from bottom to top

I have a table where I want to go from bottom to top using hierarchical queries.

The problem is that I need the get the value of one column from root (top) using CONNECT_BY_ROOT, but since I reverse the way the hierarchical query works (reverse the prior in connect by and the start with), this function (CONNECT_BY_ROOT) consider my ‘start with’ row as level 1 (root) then gets me this value.

In other words, I want a way to reverse the CONNECT_BY_ROOT to get me the value of a column from the last possible level and not the root.

I want to get the value of ID = 1 (5) to the ID = 3 like this:

I tried this but all I get is null as value_root:

EDIT: I forgot to mention that in my real system I’m dealing with millions of rows of data, the reason why I’m reversing the hierachical queries in first place is to make it better in terms of performance!

Advertisement

Answer

You may retrieve the root (which is a bottom node in your case) for all the tree upwards and then apply analytical function partitioned by the root to translate parent value to all the tree nodes. This is also possible for multiple nodes in start with.

TREE_ID ID PARENTID VAL VAL_ROOT
3 1 5 5
3 2 1 9 5
3 3 2 5
4 1 5 5
4 2 1 9 5
4 4 2 5
6 5 10 10
6 6 5 7 10
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement