Forum Discussion
WorldWide1
Helper II
9 months agoPivot(?) Help
Afternoon all -- Watched some videos and have been working this data around but can't quite get the data organized how I need it. Any help appreciated. I have a simple base table structured by ...
- 9 months ago
I agree with the others, but if you really wanted to do this in Power Query, the following code should get you started, but it will probably take a long time to execute with a large database.
let //Merge your dimension and fact tables Source = Table.NestedJoin(Table1, {"BOL"}, Table2, {"BOL"}, "Table2", JoinKind.Inner), //Expand the unique table columns #"Expanded Table2" = Table.ExpandTableColumn(Source, "Table2", {"charge_description", "charge_retail", "charge_cost"}), //unpivot #"Unpivoted Other Columns" = Table.UnpivotOtherColumns(#"Expanded Table2", {"BOL"}, "Attribute", "Value"), //Group by BOL //Generate an Index depending on the number of items in each group // You are showing five (5) items per so we divide by 5 // Then combine the various costs and the divided index to create what will be our pivoted columns #"Grouped Rows" = Table.Group(#"Unpivoted Other Columns", {"BOL"}, { {"Pivot", (t)=> [a=Table.AddIndexColumn(t,"Index",0, 1, Int64.Type), b=Table.AddColumn(a,"Costs", each Number.IntegerDivide([Index],5)+1, Int64.Type), c=Table.RemoveColumns(b,"Index"), d=Table.TransformColumnTypes(c,{"Costs", type text}), e=Table.ReplaceValue( d, each [Attribute], each [Costs], (x,y,z) as text => if y <> "Retail Price" and y <>"Cost" then y & z else y, {"Attribute"}), f=Table.RemoveColumns(e,"Costs"), g=Table.Pivot(f,List.Distinct(f[Attribute]),"Attribute","Value", List.First)][g]}}), //List all column headers so we can make sure we have them all and then // do a custom sort so they will appear in the desired order #"All Col Hdrs" = List.Distinct(List.Combine(List.Transform(#"Grouped Rows"[Pivot], each List.Skip(Table.ColumnNames(_))))), #"Sorted Col Hdrs" = [a=List.Transform(#"All Col Hdrs", each Splitter.SplitTextByCharacterTransition((c)=>not List.Contains({"0".."9"},c),{"0".."9"})(_)), b=List.Sort(a, { {each Number.From(_{1}?), Order.Ascending}, {each List.PositionOf( {"charge_description","charge_retail","charge_cost"},_{0}),Order.Ascending}}), c=List.Transform(b, each Text.Combine(_))][c], //expand the pivoted column and set the data types #"Expand Pivot" = Table.ExpandTableColumn(#"Grouped Rows","Pivot",#"Sorted Col Hdrs"), #"Changed Type" = Table.TransformColumnTypes(#"Expand Pivot", List.Transform(#"Sorted Col Hdrs", each if Text.Contains(_,"description") then {_, type text} else {_, Currency.Type})) in #"Changed Type"From your data:
lbendlin
Super User
9 months agoAs Hans-Georg_Puls mentioned this is the antithesis to what Power BI is about. Avoid merges and pivots in Power Query. Let the data model and the visuals do the work for you.