Search code examples
powerbipowerquerym

Stack columns with Power Query


I am trying to stack three columns like below on Power BI. My example dataset is following:

Processo Finalidade 1 Finalidade 2 Finalidade 3
1 Maçã Banana Mamão
2 Banana
3 Mamão Banana

However, I would like that it stay like this:

Processo Finalidade
1 Maçã
2 Banana
3 Mamão
1 Banana
2
3 Banana
1 Mamão
2
3

I tried to transpose columns but I can't this result.


Solution

  • Based on your input data and the hint in the comments I did it like that

    let
        Source = Excel.CurrentWorkbook(){[Name="tblData"]}[Content],
        Step1 = Table.TransformColumnTypes(Source,{{"Processo", Int64.Type}, {"Finalidade 1", type text}, {"Finalidade 2", type text}, {"Finalidade 3", type text}}),
        tblUnPivot = Table.ReplaceValue(Step1,null,"",Replacer.ReplaceValue,{"Finalidade 2"}),
        replaceValues = Table.ReplaceValue(tblUnPivot,null,"",Replacer.ReplaceValue,{"Finalidade 3"}),
        unpivot = Table.UnpivotOtherColumns(replaceValues, {"Processo"}, "Attribut", "Wert"),
        sorted = Table.Sort(unpivot,{{"Attribut", Order.Ascending}, {"Processo", Order.Ascending}}),
        removeCol = Table.RemoveColumns(sorted,{"Attribut"}),
        renameCol = Table.RenameColumns(removeCol,{{"Wert", "Finalidade"}})
    in
        renameCol
    

    Result looks like

    enter image description here

    But the solution strongly depends on the naming of the columns Finalidade 1 etc.

    PS Another solution which is independet of the naming of the columns could look like that

    let
        Source = Excel.CurrentWorkbook(){[Name="tblData"]}[Content],
        Step1 = Table.TransformColumnTypes(Source,{{"Processo", Int64.Type}, {"Finalidade 1", type text}, {"Finalidade 2", type text}, {"Finalidade 3", type text}}),
        tblUnPivot = Table.ReplaceValue(Step1,null,"",Replacer.ReplaceValue,{"Finalidade 2"}),
        replaceValues = Table.ReplaceValue(tblUnPivot,null,"",Replacer.ReplaceValue,{"Finalidade 3"}),
        unpivot = Table.UnpivotOtherColumns(replaceValues, {"Processo"}, "Attribut", "Wert"),
        addColumn = Table.AddColumn(unpivot, "colPos", each List.PositionOf(Table.ColumnNames(Step1),[Attribut])),
        #"Neu angeordnete Spalten" = Table.ReorderColumns(addColumn,{"Processo", "colPos", "Attribut", "Wert"}),
        removeCol1 = Table.RemoveColumns(#"Neu angeordnete Spalten",{"Attribut"}),
        sortRows = Table.Sort(removeCol1,{{"colPos", Order.Ascending}, {"Processo", Order.Ascending}}),
        renameCol = Table.RenameColumns(sortRows,{{"Wert", "Fianlidade"}}),
        removeCol2 = Table.RemoveColumns(renameCol,{"colPos"})
    in
        removeCol2