Forum Discussion

newhopepdx's avatar
newhopepdx
Resolver I
1 year ago
Solved

Table.Group problem

Given this test data:   I need to create a table (like the one shown below) that combines the names:   1. The GrpLeader field contains the PersonId of the group leader   2. The resulting Gr...
  • SamsonTruong's avatar
    SamsonTruong
    1 year ago

    Hi newhopepdx, apologies for the delay. Please try the revised solution below:

    let
        Source = YourTable,
        AddFullName = Table.AddColumn(Source, "FullName", each [FirstName] & " " & [LastName]),
    
        Grouped = Table.Group(
            AddFullName,
            {"GrpId"},
            {
                {"GroupData", each _, type table [GrpId=number, PersonId=number, GrpLeader=number, FirstName=text, LastName=text, FullName=text]}
            }
        ),
    
        AddGroupName = Table.AddColumn(Grouped, "GroupName", each
            let
                groupTable = [GroupData],
                leaderId = Record.Field(Table.First(groupTable), "GrpLeader"),
                leaderRow = Table.SelectRows(groupTable, each [PersonId] = leaderId){0},
                leaderFirst = Text.From(leaderRow[FirstName]),
                leaderLast = Text.From(leaderRow[LastName]),
                otherMembers = Table.SelectRows(groupTable, each [PersonId] <> leaderId),
                otherFirsts = List.Transform(Table.Column(otherMembers, "FirstName"), Text.From),
                lastNames = List.Distinct(List.Transform(Table.Column(groupTable, "LastName"), Text.From)),
    
                groupName =
                    if List.Count(lastNames) = 1 then
                        Text.Combine({leaderFirst} & otherFirsts, " ") & " " & lastNames{0}
                    else
                        Text.Combine(
                            List.Transform(
                                List.Combine({{leaderRow[FullName]}, Table.Column(otherMembers, "FullName")}),
                                Text.From
                            ),
                            " & "
                        )
            in
                groupName
        ),
    
        Final = Table.SelectColumns(AddGroupName, {"GrpId", "GroupName"})
    in
        Final