excelpowerquerymexcel-2021excel-pivot

How do I pivot distinct values in Excel (preferably PivotTable fields editor)?


I have a table layout with different number of text values for each id column. Now, I'd like to pivot them, so that each id gets a single row and each text value is put into a different column of the id row:

Different number of columns and values

How can I do that in Excel, preferably using PivotTable Fields editor?


Solution

  • Here's one m-code approach: Screenshot of PowerQuery window illustrating effect of proposed m code

    let
        Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
        TextID = Table.TransformColumnTypes(Source,{{"ID", Text.Type}}),
        NumCols = List.Max(Record.ToList(Table.Pivot(TextID, List.Distinct(TextID[ID]), "ID", "Text", List.Count){0})),
        txtHeads = List.Transform(List.Numbers(1, NumCols), each "Text" & Text.From(_)),
        groupRows = Table.Group(Source, {"ID"}, {{"Text", each _[Text]}}),
        extractTexts = Table.TransformColumns(groupRows, {"Text", each Text.Combine(List.Transform(List.Distinct(_), Text.From), ","), type text}),
        textSplit = Table.SplitColumn(extractTexts, "Text", Splitter.SplitTextByDelimiter(",", QuoteStyle.Csv), txtHeads),
        replaceNulls = Table.ReplaceValue(textSplit,null,"",Replacer.ReplaceValue,txtHeads)
    in
        replaceNulls