1

In Power BI's Power Query, let say I have the below table.

Customer Product 1: Type Product 1: Cost Product 2: Type Product 2: Cost
Cust 1 A $5 B $15
Cust 2 A $5 C $20

The goal is to unpivot so that there is no product 1 or product 2, just product, effectively taking the 4 columns in to 2

Customer Product Type Product Cost
Cust 1 A $5
Cust 1 B $15
Cust 2 A $5
Cust 2 C $20

I know this is fairly simple if just unpivoting from many columns to 1 column through the Unpivot columns function. But how do you go about unpivoting many columns into n columns without doing this n times and rejoining?

3
  • Is the line Cust 1 B $1 correct? Commented Aug 25, 2022 at 14:36
  • No it was a typo. Thank you for point out. This is all sample data anyway, more to show an simplified example of what I am working with Commented Aug 25, 2022 at 15:17
  • and did any of these answers help you? Commented Sep 7, 2022 at 13:27

2 Answers 2

1

You can unpivot all columns except Customer, split the Attribute values into Product and Header, then re-pivot:

let
    Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45Wci4tLlEwVNJRcgRiFVMg4QRiGJoqxepAZY2QZZ1BDCMDpdhYAA==", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [Customer = _t, #"Product 1: Type" = _t, #"Product 1: Cost" = _t, #"Product 2: Type" = _t, #"Product 2: Cost" = _t]),
    Unpivoted = Table.UnpivotOtherColumns(Source, {"Customer"}, "Attribute", "Value"),
    #"Split Attribute" = Table.SplitColumn(Unpivoted, "Attribute", Splitter.SplitTextByEachDelimiter({": "}, QuoteStyle.Csv, false), {"Product", "Header"}),
    #"Pivoted Column" = Table.Pivot(#"Split Attribute", List.Distinct(#"Split Attribute"[Header]), "Header", "Value"),
    #"Removed Columns" = Table.RemoveColumns(#"Pivoted Column",{"Product"})
in
    #"Removed Columns"

Which turns

enter image description here

into

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

After some tweaks this worked perfectly. You are the man Olly. thank you!
0

This should work also

let Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
base_columns=1, groupsof=2, // stack them
Combo = List.Transform(List.Split(List.Skip(Table.ColumnNames(Source),base_columns),groupsof), each List.FirstN(Table.ColumnNames(Source),base_columns) & _),
#"Added Custom" =List.Accumulate(
    Combo, 
    #table({"Column1"}, {}),
    (state,current)=> state & Table.Skip(Table.DemoteHeaders(Table.SelectColumns(Source, current)),1))
in #"Added Custom"

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.