Here's the query I used to generate the index column in the question:
let
// This has the original parent/child column
Source = #"Parent Child Query",
// Count the number of parents per child
#"Grouped Rows" = Table.Group(Source, {"Attribute:id"}, {{"Count", each Table.RowCount(_), type number}}),
// Add a new column of lists with the indexes per child
#"Added Custom" = Table.AddColumn(#"Grouped Rows", "ParentIndex", each List.Numbers([Count], [Count], -1)),
// Expand the lists in the previous step
#"Expand ParentIndex" = Table.ExpandListColumn(#"Added Custom", "ParentIndex"),
// Create the column name columns (Parent.1, Parent.2, etc)
#"Added Custom1" = Table.AddColumn(#"Expand ParentIndex", "ParentColumn", each "Parent."&Text.From([ParentIndex])),
// Adds an index column that you use when merging with the original table
#"Added Index" = Table.AddIndexColumn(#"Added Custom1", "Index", 0, 1)
in
#"Added Index"
Once this was done I created another query to hold the merged result:
let
// This is the original parent/child column
Source = #"Parent Child Query",
// Add an index column that matches the index column in the previous query
#"Added Index" = Table.AddIndexColumn(Source, "Index", 0, 1),
// Merge the two queries based on the index columns
Merge = Table.NestedJoin(#"Added Index",{"Index"},#"Epic Parent Indices",{"Index"},"NewColumn"),
// Expand the new column
#"Expand NewColumn" = Table.ExpandTableColumn(Merge, "NewColumn", {"ParentColumn"}, {"ParentColumn"}),
// Remove the index column
#"Removed Columns" = Table.RemoveColumns(#"Expand NewColumn",{"Index"}),
// Sort the data by attribute and then by Parent column so the columns will be in the right order
#"Sorted Rows" = Table.Sort(#"Removed Columns",{{"Attribute:id", Order.Descending}, {"ParentColumn", Order.Ascending}}),
// Pivot!
#"Pivoted Column" = Table.Pivot(#"Sorted Rows", List.Distinct(#"Sorted Rows"[ParentColumn]), "ParentColumn","Parent:id")
in
#"Pivoted Column"
There were three key steps here:
- Use Table.Group to get the number of parents per child element.
- Use List.Numbers to get index values for each parent/child relationship.
- Use Table.AddIndexColumn to add index columns to be used as the key in the call to Table.Join If you don't do this then you'll get duplicate data in the merge.