Power Query:如何透视表

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

我真的需要你的帮助

我想更改这个表(表一)

对于表一,数字下方的所有文本都将指向曼彻斯特,文本下方的所有文本将指向阿森纳。这就是为什么如果您看到单元格(2,阿森纳)或(5,阿森纳),您将看到空白或空单元格。

我需要这样的桌子

pivot powerquery
1个回答
0
投票

在 Power Query 中,一种方法:

  • 添加包含(我假设)团队或 null 的自定义列,具体取决于第 1 列前一行中的值是否为数字。
  • 按第 1 列中数值的每个变化进行分组
  • 旋转每个子组。
  • 展开子表

请阅读代码注释并探索

Applied Steps
以更好地理解算法

原始数据

M代码
粘贴到高级编辑器
更改

Source
以反映您的实际数据源

let
    Source = Excel.CurrentWorkbook(){[Name="Table2"]}[Content],

//Add a shifted column so as to be able to compare current row of 
//  Column1 with the row above
//Could also do this by adding an Index column, but this method is usually faster
    #"Add Shifted Column" = Table.FromColumns(
        Table.ToColumns(Source) & 
        {{null} & List.RemoveLastN(Source[Column1])}),

//Add a column which enters the relevant "Team" in a custom column1
    #"Add Team Column" = Table.AddColumn(#"Add Shifted Column", "Team", each 
        if not (try Number.From([Column1]))[HasError] then null 
        else if (try Number.From([Column1]))[HasError] and not (try Number.From([Column2]))[HasError] then "Manchester"
        else "Arsenal", type nullable text),

//Remove Column2 (the "Shifted" column
    #"Removed Columns" = Table.RemoveColumns(#"Add Team Column",{"Column2"}),

//Group by the numeric value in Column 1
// Then Pivot each subtable
//Note use of GroupKind.Local and the optional 5th argument of the Table.Group function
    #"Grouped Rows" = Table.Group(#"Removed Columns", {"Column1"}, {
        {"Pivot", each Table.Pivot(_, List.Distinct(List.RemoveNulls([Team])),"Team","Column1" ),
            type table[Column1=number, Manchester=nullable text, Arsenal=nullable text]    }
        }, GroupKind.Local,(x,y)=> try Number.From(y[Column1]) otherwise 0),

//Expand the tables
    #"Expanded Pivot" = Table.ExpandTableColumn(#"Grouped Rows", "Pivot", {"Manchester", "Arsenal"})
in
    #"Expanded Pivot"

结果

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