Skip to content
Advertisement

Create parent/child relation in SQL server based on the below scenario

enter image description here

In this picture, 2018_9UKDT – UKD Expense Total is parent of 2018_9Q400 – UKD Indirects and this in turn is parent to 98064 – IT SDS Costs, 98063 – ACS in charges, 98012 – UKD – Central.

Could someone let me know how to create parent child relation using T-SQL which has upto 10 levels.

Table creation

and the output would be in the below attached screen shot. Basically from least level to increasing order.

enter image description here

Advertisement

Answer

Since you know you have a max level of 10, you can use a couple of common table expressions and conditional aggregation:

Results (for the sample data posted on the question):

Please note that for multiple root nodes, it will be difficult to know where the root node is (basically, you could have Level1, Level2 … as null, where at least one other node have more children.

Therefor, you should probably have the root node on the left most column. To do that, change the dense_rank order by from DESC to ASK, and the condition on the subquery in the second cte from WHERE T1.Level > T0.Level to WHERE T1.Level < T0.Level.

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