How to convert flattened hierarchy to Parent child hierarchy?

Shivendoo Kumar 736 Reputation points
2020-09-15T07:27:50.28+00:00

Hi All,
I have a flattened hierarchy table like this and I want to convert this to Parent child hierarchy table to use into TM1. Benefit of converting from flattened hierarchy to Parent child hierarchy table is that if tomorrow we add few more new Hierarchy Levels, no change required on TM1.

Would like to know T-SQL query to convert this:

flattened hierarchy table: Here Account_HL1 is top Level and Account is bottom level in Hierarchy.
24805-image.png

and I am looking for outcome like Parent child hierarchy table:
24787-image.png

I found this https://stackoverflow.com/questions/16879568/how-can-i-convert-the-following-flat-records-to-a-hierarchical-structure-in-sql
but here it is done using Union and would like to know are there any other ways so that this can be done dynamically considering there can be more levels added in future.

Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,564 questions
{count} vote

1 answer

Sort by: Most helpful
  1. EchoLiu-MSFT 14,571 Reputation points
    2020-09-15T08:02:12.353+00:00

    Hi @Shivendoo Kumar
    Please refer to:

    declare @test table(col1 char(25),col2 char(25),col3 char(25),col4 char(25),amount int)  
        insert into @test values('storeprofit','grossprofit','netsales','sales',2222),  
                                ('storeprofit','grossprofit','purchases','purchases',2223),  
         ('storeprofit','totaldirectcosts','employeeexpenses','spuer',2224),  
         ('storeprofit','totaldirectcosts','occupancyexpenses','rent&rates',2225),  
         ('storeprofit','totaldirectcosts','advertisingexpenses','advertisingexpenses',2226)  
    select null parent,max(col1) child,1 as level from @test  
    union all  
    select distinct col1 parent, col2 child,2 as level from @test  
    union all  
    select distinct col2 parent, col3 child,3 as level from @test  
    union all  
    select distinct col3 parent, col4 child,4 as level from @test  
    union all  
    select distinct col4 parent, cast(amount as char(15))child,5 as level from @test   
    

    24827-image.png

    Best Regards
    Echo


    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.
    0 comments No comments