使用 Excel 将成对的关联列逆透视到行

问题描述 投票:0回答:1

我有一个 Excel 表格,其中包含如下交错的商品价格:

ArtNr   Amount1   Price1   Amount2   Price2   Amount3   Price3
--------------------------------------------------------------
4711          1      3.5         5      3.0        10      2.5
4712          1      5.0         3      4.5         5      4.0
4713          1      7.0        10      6.0       100      5.0

我想将其转变成这个结构:

ArtNr   Amount   Price
----------------------
4711         1     3.5
4711         5     3.0
4711        10     2.5
4712         1     5.0
4712         3     4.5
4712         5     4.0

... 可以使用 Power Query 或在 Excel 中通过 Excel 中的 PIVOT/UNPIVOT 来完成此操作吗?

我需要一个具有 Excel 精确结果的解决方案

excel sorting datatable unpivot
1个回答
0
投票

这是使用 Power Query 执行此操作的方法。
将此代码粘贴到高级编辑器中,按照指示对数据源进行更改。
阅读代码注释以理解算法。

let

//change next line to reflect actual table source
    Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],

//Unpivot except for ArtNr column        
    #"Unpivoted Other Columns" = Table.UnpivotOtherColumns(Source, {"ArtNr"}, "Attribute", "Value"),

//Remove the terminal digits from the column names in the Attribute column
    #"Remove Trailing Digits" = Table.SplitColumn(#"Unpivoted Other Columns", "Attribute", 
        Splitter.SplitTextByCharacterTransition((c) => not List.Contains({"0".."9"}, c), {"0".."9"}), {"Attribute"}),

//Create column for grouping
    #"Added Index" = Table.AddIndexColumn(#"Remove Trailing Digits", "Index", 0, 1, Int64.Type),
    #"Add Grouper Column" = 
        Table.AddColumn(#"Added Index", "Grouper", each Number.IntegerDivide([Index], 2), Int64.Type),
    #"Removed Columns" = Table.RemoveColumns(#"Add Grouper Column",{"Index"}),

//Group, then Pivot each subtable with no aggregation
    #"Grouped Rows" = Table.Group(#"Removed Columns", {"Grouper"}, {
        {"Pivot", each Table.Pivot(Table.RemoveColumns(_,"Grouper"),[Attribute],"Attribute","Value"),
            type table[ArtNr=Int64.Type, Amount=Int64.Type, Price=number]
        }}),

//Remove the now unneeded grouper column, then expand the pivotted tables
    #"Removed Columns1" = Table.RemoveColumns(#"Grouped Rows",{"Grouper"}),
    #"Expanded Pivot" = Table.ExpandTableColumn(#"Removed Columns1", "Pivot", {"ArtNr", "Amount", "Price"})
        
in
    #"Expanded Pivot"

© www.soinside.com 2019 - 2024. All rights reserved.