问题
I have a problem I need to solve in power query.
I have table containing columns Name, ID and Parent ID
Name ID Parent
A 1
B 2 1
C 3 1
D 4 2
E 5 2
I need to transform this table so that I get one row for each child (and orginal) that row has. In this example this would yield 11 rows.
Name ID
A 1
A 2
A 3
A 4
A 5
B 2
B 4
B 5
C 3
etc.
I know this is done with some sort of joining but it feels like a loop and I don't know how to do loops in Power Query.
回答1:
A friendly reddit user created solution for this.
(ID as list, CurrentItem as number, FullTable as table) as list =>
let
CurrentID = ID{CurrentItem},
ParentRows = Table.SelectRows(FullTable, each [Parent] = CurrentID),
AddNodes = if Table.RowCount(ParentRows) > 0 then List.Distinct(ID & ParentRows[ID]) else ID,
FinalResult = if (List.Count(ID) = List.Count(AddNodes)) and CurrentItem = List.Count(ID) - 1 then ID else BuildNodes(AddNodes, CurrentItem + 1, FullTable)
in
FinalResult
回答2:
Try this,not necessarily right,please check it.Does anyone else have a better solution?
let
Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
Top = Table.SelectRows(Source, each ([Parent] = null)),
Path = Table.AddColumn(Top, "Path", each #table({"Name","ID"},{{[Name],[ID]}})),
Loop = Table.Combine(List.Generate(()=>
Path,
each not Table.IsEmpty(_),
each [
a = Table.NestedJoin(Source,{"Parent"},_,{"ID"},"join",JoinKind.Inner),
b = Table.ExpandTableColumn(a, "join", {"Path"}, {"Pre_Path"}),
c = Table.AddColumn(b,"Path", each [Pre_Path]&Table.Group([Pre_Path],"Name",{"ID",(x)=>[ID]})&#table({"Name","ID"},{{[Name],[ID]}}))
][c]
)),
Result = Table.Distinct(Table.Combine(Loop[Path])),
Sort = Table.Buffer(Table.Sort(Result,{{"Name",0}, {"ID",0}}))
in
Sort
Power Pivot is much easier,you can use PATH to solve the problem of Parent-Child Hierarchy.
来源:https://stackoverflow.com/questions/50561542/power-query-child-hierarcy