Forum Discussion

Anonymous's avatar
Anonymous
Not applicable
5 years ago
Solved

Power Query code to find parent

Hi all!    I have a table containing a hierarchal breakdown of employees as the one shown below:   Level Name 1 Person 1 2 Person 2 3 Person 3 3 Person 4 3 Person 5 4 ...
  • AlB's avatar
    5 years ago

    Anonymous 

    Ok. You can just keep the first item in the list then:

    let
        Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WMlTSUQpILSrOz1MwVIrViVYyQggYgQWMEQLG6AIm6AKmYAEThIAZuoA5uhYLdAFLdHcYGqArMQS6NRYA", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [Level = _t, Name = _t]),
        #"Changed Type" = Table.TransformColumnTypes(Source,{{"Level", Int64.Type}, {"Name", type text}}),
    
        #"Added Custom" = Table.AddColumn(#"Changed Type", "Parent", each try Table.SelectRows(#"Changed Type", (inner)=>inner[Level]=[Level]-1)[Name]{0} otherwise null, type text)
    in
        #"Added Custom"

     

    Please mark the question solved when done and consider giving a thumbs up if posts are helpful.

    Contact me privately for support with any larger-scale BI needs, tutoring, etc.

    Cheers 

     

  • AlB's avatar
    5 years ago

    Anonymous 

    Then we need to add an index to establish that order:

    let
        Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WMlTSUQpILSrOz1MwVIrViVYyQggYgQWMEQLG6AIm6AKmYAEThIAZuoA5uhYLdAFLdHcYGqArMQS6NRYA", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [Level = _t, Name = _t]),
        #"Changed Type" = Table.TransformColumnTypes(Source,{{"Level", Int64.Type}, {"Name", type text}}),
    
        #"Added Index" = Table.AddIndexColumn(#"Changed Type", "Index", 1, 1, Int64.Type),
        #"Added Custom" = Table.AddColumn(#"Added Index", "Parent", each try List.Last(Table.SelectRows(#"Added Index", (inner)=>inner[Level]=[Level]-1 and inner[Index]<[Index])[Name]) otherwise null, type text),
        #"Removed Columns" = Table.RemoveColumns(#"Added Custom",{"Index"})
    in
        #"Removed Columns"

    It would have helped if you had shown the expected result from the beginning

     

    Please mark the question solved when done and consider giving a thumbs up if posts are helpful.

    Contact me privately for support with any larger-scale BI needs, tutoring, etc.

    Cheers