如何将 table 压平成一行?

How to flatten a table into one single row?

是否可以使用 PowerQuery 将左侧的 table 转换为右侧的 table?

不要介意除 Table1 之外的标签,因为它们已经存在于目标中。

在现实生活中,Table1 将是一个 Excel sheet,我必须将其中许多(Table1 到 Table50)展平,每个都变成一行:

我试过这个:

  1. 取消透视 Aspect1/Aspect2 列。
  2. 已将 Aspect1/2 的属性列与 CAT1-5 列合并。
  3. 转置 table.
  4. 将其提升为 headers。

我得到了Aspect1:Cat1; Aspect2:Cat1; Aspect2:Cat1; Aspect2:Cat2;...

而不是Aspect1:Cat1; Aspect1:Cat2; ... Aspect2:Cat1; Aspect2;Cat2...

为了澄清,我需要:Aspect1 与所有类别合并,然后 Aspect2 与所有类别合并,依此类推。

如果你只是添加一个排序步骤(见下面的 4),我的建议看起来你已经明白了。


  1. 逆透视 ASPECT 列
  2. 将 ASPECT 和 CATEGORY 连接为一个新列
  3. 删除 ASPECT 和 CATEGORY 列
  4. 按连接列排序
  5. 转置 table
  6. 提升headers

完整的 M 查询:

let
    Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WcnYMMVTSUTKxVAWSxuaqSrE6YEEjINfUECRoZAgXNAZxzUCChghBE5B2Y5AgQrcpkGdpChIzAwnGAgA=", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [CATEGORY = _t, ASPECT1 = _t, ASPECT2 = _t]),
    #"Changed Type" = Table.TransformColumnTypes(Source,{{"CATEGORY", type text}, {"ASPECT1", Percentage.Type}, {"ASPECT2", Percentage.Type}}),
    #"Unpivoted Columns" = Table.UnpivotOtherColumns(#"Changed Type", {"CATEGORY"}, "ASPECT", "Value"),
    #"Added Custom" = Table.AddColumn(#"Unpivoted Columns", "ASPECT_CAT", each [ASPECT] & "; " & [CATEGORY], type text),
    #"Removed Other Columns" = Table.SelectColumns(#"Added Custom",{"ASPECT_CAT", "Value"}),
    #"Sorted Rows" = Table.Sort(#"Removed Other Columns",{{"ASPECT_CAT", Order.Ascending}}),
    #"Transposed Table" = Table.Transpose(#"Sorted Rows"),
    #"Promoted Headers" = Table.PromoteHeaders(#"Transposed Table", [PromoteAllScalars=true]),
    #"Changed Type1" = Table.TransformColumnTypes(#"Promoted Headers",{{"ASPECT1; CAT1", Percentage.Type}, {"ASPECT1; CAT2", Percentage.Type}, {"ASPECT1; CAT3", Percentage.Type}, {"ASPECT1; CAT4", Percentage.Type}, {"ASPECT1; CAT5", Percentage.Type}, {"ASPECT2; CAT1", Percentage.Type}, {"ASPECT2; CAT2", Percentage.Type}, {"ASPECT2; CAT3", Percentage.Type}, {"ASPECT2; CAT4", Percentage.Type}, {"ASPECT2; CAT5", Percentage.Type}})
in
    #"Changed Type1"