Sunday, September 8, 2013

[T-SQL] Flatten a hierarchy table

[T-SQL] Flatten a hierarchy table


Flatten a hierarchy table

Posted: 07 Sep 2013 02:09 PM PDT

I want to write a query to flatten the hierarchy of a table and I don't know what's best way to do it.Here' s something about the data I am dealing with:We know Manager-Employee table is a typical example of table with parent_child relationship, we can easilyuse a recursive CTE to find the hierarchy relationship with different hierarchy level. If we treat Manager-employee as one company that has parent-child relationship then the table I am currently dealing with will be a table contains many companies that I need to find the hirarchy relationship for each one of the company in the table and companies in the table has no relationship with each other.The final output will be the union of recursive CTE for each company.If the table contains A, B, C, D and E five companiesthe output will beRecursive CTE_A union Recursive CTE_B unoin Recursive CTE_C ...union Recursive CTE_Eapparently in the real table it contains millions of individual records or companies.What's the best way to achieve it?Thank you!

No comments:

Post a Comment

Search This Blog