Forum Discussion
PowerQuery Pivot Multiple Columns/Categories
- 5 years ago
Hi, greenguy2012
Based on your description, I created data to reproduce your scenario. The pbix file is attached in the end.
You may create a new query with the following m codes in 'Advanced Editor'.
let #"Pivoted Column 1" = Table.Pivot(Table, List.Distinct(Table[Category]), "Category", "Sales Month"), Custom1 = Table.Group(#"Pivoted Column 1",{"Region","Sales Rep"},{{"Retail Month",each List.First(List.RemoveNulls([Retail]))},{"Channel Month",each List.First(List.RemoveNulls([Channel]))}}), #"Pivoted Column 2" = Table.Pivot(Table, List.Distinct(Table[Category]), "Category", "Sales Amount", List.Sum), Custom2 = Table.Group(#"Pivoted Column 2",{"Region","Sales Rep"},{{"Retail Sales Amount",each List.First(List.RemoveNulls([Retail]))},{"Channel Sales Amount",each List.First(List.RemoveNulls([Channel]))}}), Res = Table.NestedJoin(Custom1, {"Region", "Sales Rep"}, Custom2, {"Region", "Sales Rep"}, "Res Table", JoinKind.Inner), #"Expanded Res Table" = Table.ExpandTableColumn(Res, "Res Table", {"Retail Sales Amount", "Channel Sales Amount"}, {"Retail Sales Amount", "Channel Sales Amount"}), #"Sorted Rows" = Table.Sort(#"Expanded Res Table",{{"Retail Month", Order.Ascending}}), #"Reordered Columns" = Table.ReorderColumns(#"Sorted Rows",{"Region", "Sales Rep", "Retail Month", "Retail Sales Amount", "Channel Month", "Channel Sales Amount"}) in #"Reordered Columns"Result:
Best Regards
Allan
If this post helps, then please consider Accept it as the solution to help the other members find it more quickly.
Hi greenguy2012
Why do you need to do this? The structure you want to change your data into breaks away from the ideal layout that it is in. You are adding columns and introducing nulls.
What is the final aim of this? Can't you do it with the data as it is already structured?
Regards
Phil
Hi Philip, it's a requirement from my stakeholders unfortunately.
- PhilipTreacy5 years agoSuper User
Hi greenguy2012
I understand, it's just bad practice. Do your stakeholders really need the data arranged like this? Shouldn't the data stay in the best format to allow easier reporting and not cause issues down the line?
If the aim is to report Retail sales and Channel sales separately, this can already be done with the data as it is.
Regards
Phil
- greenguy20125 years agoAdvocate I
The requirement is for the green table unfortunately. I appreciate the help!