I have an Input table with two columns as below. The Parent ID and Child ID columns will have a hierarchical structure.
##Input Table
| ParentID | ChildID |
|---|---|
| PR001 | CR001 |
| PR001 | CR002 |
| PR001 | CR003 |
| CR001 | DR001 |
| CR001 | DR002 |
| CR002 | DR003 |
| DR001 | ER001 |
| DR002 | ER002 |
| ....... | ...... |
| XXXXX | YYYYY |
I've applied recursive CTE method to generate the intermediate output to include level column based on the hierarchical structure
##Intermediate Output Table:
| ParentID | ChildID | Level |
|---|---|---|
| PR001 | CR001 | 1 |
| PR001 | CR002 | 1 |
| PR001 | CR003 | 1 |
| CR001 | DR001 | 2 |
| CR001 | DR002 | 2 |
| CR002 | DR003 | 3 |
| DR001 | ER001 | 3 |
| DR002 | ER002 | 3 |
| ....... | ...... | ... |
| XXXXX | YYYYY | N |
I'm trying to generate the final output by pivoting the values based on the hierarchical structure of the intermediate output. The number of columns with level prefixed by its value will be based on the level column.
##Desired Result:
| ID | Level 1 | Level 2 | Level 3 | Level....N |
|---|---|---|---|---|
| PR001 | CR001 | DR001 | ER001 | |
| PR001 | CR001 | DR002 | ER002 | |
| PR001 | CR002 | DR003 | ||
| PR001 | CR003 | |||
| XXXX | XXXX | YYYY |
Tried to apply pivot as below but it's not helping
SELECT ParentID, ChildID
FROM
(SELECT ParentID, ChildID, Level from table_1>)
AS src
PIVOT
(
count (ParentID)
FOR [Level]
IN ( '1' as 'Level_1', '2' as 'Level_2', '3' as 'Level_3' ])
) AS pvt ;
Is there any functions to apply in SQL Server for this case?
I will propose a solution with recursion and a fixed number of columns (levels). Increasing the number of levels is not difficult.
A solution with an unlimited number of levels can only be performed through a dynamic query.
Output
with test data
Test fiddle here