Forum Discussion

dpwhitey1's avatar
dpwhitey1
Frequent Visitor
3 years ago
Solved

How to pivot Multiple Columns

Hello   Is there an easy way to use Power Query to pivot data with a Unique ID spread over multiple rows, into a spreadsheet with one row per ID? eg I have 22 milestones below, each milestone has ...
  • ronrsnfld's avatar
    ronrsnfld
    3 years ago

    Assuming all of the ID's have all of the Milestone's listed in proper order, You can:

    • Group by ID
    • For each sub-table
      • Select the ID and Milestone columns and UNPIVOT other columns
      • Merge the Milestone and Attribute column => the new column headers
      • Remove the original columns and more the new merged column to Column2
      • Transpose the resultant table
        • Remove the top row and make the next row the new headers
    • Re-Expand the grouped table

    In the code below, change line 2 to reflect your actual data source

    let
        Source = Excel.CurrentWorkbook(){[Name="Table7"]}[Content],
        #"Changed Type" = Table.TransformColumnTypes(Source,{{"ID", Int64.Type}, {"Milestone", type text}, {"Actual Completion Date", type date}, {"Actual Start Date", type date}, {"Active", type text}, {"Activity Status", type text}}),
        #"Grouped Rows" = Table.Group(#"Changed Type", {"ID"}, {
            {"Transpose", (t)=>
                let 
                    #"Unpivoted Other Columns" = Table.UnpivotOtherColumns(t, {"ID", "Milestone"}, "Attribute", "Value"),
                    #"Inserted Merged Column" = 
                        Table.AddColumn(
                            #"Unpivoted Other Columns", "Merged", each Text.Combine({[Milestone], [Attribute]}, " - "), type text),
                    #"Removed Columns" = Table.RemoveColumns(#"Inserted Merged Column",{"Milestone", "Attribute"}),
                    #"Reordered Columns" = Table.ReorderColumns(#"Removed Columns",{"ID", "Merged", "Value"}),
                    #"Transposed Table" = Table.Transpose(#"Reordered Columns"),
                    #"Removed Top Rows" = Table.Skip(#"Transposed Table",1),
                    #"Promoted Headers" = Table.PromoteHeaders(#"Removed Top Rows", [PromoteAllScalars=true])
                in #"Promoted Headers"}}),
    
        #"Column Names" = Table.ColumnNames(#"Grouped Rows"[Transpose]{0}),
        #"Data Types" = List.Transform(#"Column Names", each if Text.EndsWith(_, "Date") then {_, type date} else {_, type text}), 
        #"Expanded Transpose" = Table.ExpandTableColumn(#"Grouped Rows", "Transpose", #"Column Names"),
        #"Set Data Types" = Table.TransformColumnTypes(#"Expanded Transpose", #"Data Types")
    in
        #"Set Data Types"